Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

July 15, 2013

Parameters in C# code example


Set of arguments that must be provided for that method are parameters 

  Different ways of passing parameters in C# 
               Pass by Value (Value Of Parameter Passed)
      Pass by ref  (Memory Location or Ref of Parameter is passed)
      Out (  variable is assigned a value before returning from a method)
      Params (  any number of parameters of a particular type)

See the below code example 
    



using System;
using System.Text;
class Test
{
    static void DisplayUsingValue(int p) { ++p; }
    static void DisplayUsingRef(ref int p) { ++p; }
    static void DisplayUsingOut(int p , out int y)
    {

        y=p+2;
    }
    static int Add(params int[] iarr)
    {
        int sum = 0;
        foreach (int i in iarr)
            sum += i;
        return sum;
    }



    static void Main()
    {
        int x = 8;
        DisplayUsingValue(x); // make a copy of the value-type x
        Console.WriteLine("output From Pass By Value Method Demo  ");
        Console.WriteLine(x); // x will still be 8

        DisplayUsingRef(ref x);
        Console.WriteLine("output From Pass By Ref Method Demo  ");
        Console.WriteLine(x);

        int a;
        DisplayUsingOut(x, out a);
        Console.WriteLine("output From out parameter  Demo  ");
        Console.WriteLine(a);

        int result = Add(1, 2,7);
        Console.WriteLine("output From params[]  Demo  ");
        Console.WriteLine(result);

    }
}


And See the output 
"output From Pass By Value Method Demo
8
output From Pass By Ref Method Demo
9
output From out parameter  Demo 
11
output From params[]  Demo 
10

February 20, 2012

String to DateTime Conversion ( in format "MM/dd/yyyy") in C#

Below sample code can be used to convert a string in to DateTime in MM/dd/yyyy format.



            DateTime dateValue;
            if (DateTime.TryParseExact(txtPassword.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue))
            {
                DateTimeFormatInfo dtfi = new DateTimeFormatInfo();
                dtfi.ShortDatePattern = "MM/dd/yyyy";
                dtfi.DateSeparator = "/";


              DateTime convertedDate= Convert.ToDateTime(txtPassword.Text, dtfi);
            } 


November 4, 2011

Ref Keyword(argument passed by reference) Example in C#


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace Ref_Key_Word
{
        class TestRef
        {
            //Pass by Value
            public static void TestWithoutRef(int i)
            {
            i++;
            }


            //Pass by reference
            public static void TestWithRef(ref int i) // note ref
            {
                i++;
            }


            public static void Main()
            {
                //a value will not change after calling a method as is is pass by value
                int a = 2;
                TestWithoutRef(a);
                Console.WriteLine("The value of a is " + a);


                //b value will be chnaged( as it is pass by ref 
                int b = 2;
                TestWithRef(ref b);
                Console.WriteLine("The value of b is " + b);
            }
        }




           
}
Below will be the o/p

October 8, 2011

Nested Class and Static Nested Class


//Static Nested Class
using System;
public class A
{
    int y;


    public static class B
    {
         static  int x;
       public static void F()
        {
            x = 10;
            Console.WriteLine("IN B  , X is"+x);
        }
    }
}
class Program
{
    public static void Main()
    {
        A.B.F();


    }
}

//Non Static Nested Class

using System;
public class A
{
    int y;


    public  class B
    {
        int x;
       public  void F()
        {
            x = 10;
            Console.WriteLine("IN B  , X is"+x);
        }
    }
}


class Program
{
    public static void Main()
    {
        A.B obj = new A.B();
        obj.F();
    }
}

October 4, 2011

CodeExample for out modifier in C#


out modifier requires that a variable is assigned a value before 
returning from a method
using System;
class Test {
  static void Split(string name, out string firstNames, 
                    out string lastName) {
     int i = name.LastIndexOf(' ');
     firstNames = name.Substring(0, i);
     lastName = name.Substring(i+1);
  }
  static void Main( ) {
    string a, b;
    Split("Sachin Tendulkar", out a, out b);
    Console.WriteLine("FirstName:{0}, LastName:{1}", a, b);
  }
}

October 2, 2011

Code Snippet to Bind YearList


  public void GetYearList(DropDownList ddlYearList)
    {
        int i = DateTime.Now.Year;
        for (i = i - 1; i <= DateTime.Now.Year + 3; i++)
            ddlYearList.Items.Add(Convert.ToString(i));


      
    }

Code Snippet to Bind MonthList


 public void GetMonthList(DropDownList ddlMonthList)
    {
        DateTime month = Convert.ToDateTime("1/1/2000");
        for (int i = 0; i < 12; i++)
        {


            DateTime NextMonth = month.AddMonths(i);
            ListItem list = new ListItem();
            list.Text = NextMonth .ToString("MMMM");
            list.Value = NextMonth .Month.ToString();
            ddlMonthList.Items.Add(list);
        }
       




    }

August 10, 2011

code for screen scraping with Html Agility Pack

Html Agility Pack  is a .NET code library that allows you to parse "out of the web" HTML files.
If you want to scrap some data from HTMl file over the we this is the easiest solution .
The only problem is you are dependent on third party , IF they change the structure , then you have to again work around with the changes.

Below is the sample code I am writing to for this
1.) To use Html Agility Pack download it from the below path

2.) Add the reference of HTMLAgilityPack.dll from the above downloaded folder in your bin folder of the ASP.NET solution.


3.) See the below code to read the data using this in you Class




using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;
using HtmlAgilityPack;
public partial class GetGoldPrice : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
           FindDIVFromHTMLOnWeb();


    }
    private void FindDIVFromHTMLOnWeb()
    {
        HtmlWeb web = new HtmlWeb();
        HtmlDocument doc = web.Load("http://www.testdomain.com");
        HtmlNode dataNode = doc.DocumentNode.SelectSingleNode("//div[@id='[id of the div to be fetched]']");
        string data = dataNode.InnerText;
        Response.Write(data);




    }
}

July 30, 2011

Code Snippet to create a div dynamically in C#



System.Web.UI.HtmlControls.HtmlGenericControl DivObj =
        new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
    DivObj .ID = "DIV1";
    DivObj .Style.Add(HtmlTextWriterStyle.BackgroundColor, "Red");
    DivObj .Style.Add(HtmlTextWriterStyle.Height, "10px");
    DivObj .Style.Add(HtmlTextWriterStyle.Width, "200px");
    DivObj .InnerHtml = "Some Text";
    this.Controls.Add(DivObj) ;

June 23, 2011

Code Example for Anonymous type and Type Inference in C#


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication7
{
   class Program
    {
        static void Main(string[] args)
        {
            var P = new { firstname = "ABC" };//P object of anonymost class 
            Console.WriteLine(P.firstname);
        }
    }
}

Code example for Collection Initializers – C# 3.0

Quick way to add items in collection
below is the example


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication7
{
  public   class Person
    {
        private string _firstName;
        public string firstName{get { return _firstName; }set { _firstName = value;} }
            
        
    }




    class Program
    {
        static void Main(string[] args)
        {
            List<Person> obj=new List<Person> 
            {
                new Person {firstName ="ABC"},
                new Person {firstName ="Test"}


            };


            foreach (Person p in obj)
            {
                Console.WriteLine(p.firstName);




            }
        }
    }
}

Object Initializers – C# 3.0

lQuick way to create an instance and set a bunch of properties

See the below example


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication7
{
    class Person
    {
        private string _firstName;
        public string firstName{get { return _firstName; }set { _firstName = value;} }
            
        
    }
    class Program
    {
        static void Main(string[] args)
        {
            Person obj = new Person { firstName = "ABC" };
            Console.WriteLine(obj.firstName);
        }
    }
}

June 20, 2011

Code Example for Interface and Abstract Class in C#


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication2
{




    interface EMPLOYEE
    {
         int GetID
        {
            get;


            set;
        }


         string GetName
         {
             get;


             set;
         }




         string  GetDepName
         {
             get;
         }


         int GetDepID
         {
             get;
         }
    }




    public  abstract class EMP:EMPLOYEE 
    {
        int ID;
        String  NAME;


        public EMP()
        {


        }
       public EMP(int id,String name)
        {
            this.ID =id;
            this.NAME = name;


        }
        public  int GetID
        {
            get{


                return this.ID;
            }


            set{


                this.ID=value ;
            }
        }


        public string  GetName
        {
            get
            {


                return this.NAME ;
            }
            set
            {


                this.NAME = value;
            }
        }




           public abstract string  GetDepName
           {
            get;
           }


         public  abstract  int GetDepID
        {
            get;
        }
       
    }


    public class SalesEmp : EMP
    {
        int DepartmentID;
        String DepartmentName;


        public SalesEmp()
        {


        }
        public SalesEmp(int DepId,String DepName)
        {
            this.DepartmentID = DepId;
            this.DepartmentName = DepName;


        }
      
        public override  int GetDepID
        {
            get
            {


                return this.DepartmentID;
            }
        }


        public override  string GetDepName
        {
            get
            {


                return this.DepartmentName;
            }
        }


    }




    public class TechEmp : EMP
    {
        int DepartmentID;
        String DepartmentName;


        public TechEmp()
        {


        }
        public TechEmp(int DepId, String DepName)
        {
            this.DepartmentID = DepId;
            this.DepartmentName = DepName;


        }


        public override int GetDepID
        {
            get
            {


                return this.DepartmentID;
            }
        }


        public override string GetDepName
        {
            get
            {


                return this.DepartmentName;
            }
        }


    }


    
    class Program
    {
        static void Main(string[] args)
        {
            EMPLOYEE se = new SalesEmp(1, "SALE");
            EMPLOYEE te = new TechEmp (2,"TECHNICAL");


            se.GetName = "EMP1";
            se.GetID = 1;


            te.GetName = "EMP2";
            te.GetID = 2;


            Program obj = new Program();
            obj.EmployeeBelongTo(se);
            obj.EmployeeBelongTo(te);
        }


        public void EmployeeBelongTo(EMPLOYEE E)
        {


            Console .WriteLine ("{0} belongs to {1} department",E.GetName,E.GetDepName);
        }
    }






}

code example for Upcasting/Downcasting in C#


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication2
{


    public  class EMP
    {
        int ID;
        String  NAME;


        public EMP()
        {


        }
       public EMP(int id,String name)
        {
            this.ID =id;
            this.NAME = name;


        }
        public  int GetID
        {
            get{


                return this.ID;
            }


            set{


                this.ID=value ;
            }
        }


        public string  GetName
        {
            get
            {


                return this.NAME ;
            }
            set
            {


                this.NAME = value;
            }
        }


       
    }


    public class SalesEmp : EMP
    {
        int DepartmentID;
        String DepartmentName;


        public SalesEmp()
        {


        }
        public SalesEmp(int DepId,String DepName)
        {
            this.DepartmentID = DepId;
            this.DepartmentName = DepName;


        }
      
        public int GetDepID
        {
            get
            {


                return this.DepartmentID;
            }
        }


        public string GetDepName
        {
            get
            {


                return this.DepartmentName;
            }
        }


    }








    class Program
    {
        static void Main(string[] args)
        {
            EMP e = new EMP();
            SalesEmp se = new SalesEmp(1, "SALE");


            e = se;//upcasting




            if (se is EMP)
            {
                se.GetName = "ABC";
                se.GetID = 123;


            }


            SalesEmp s1 = (SalesEmp)e;//downcasting
           
            Console.WriteLine(s1.GetID);
            Console.WriteLine(s1.GetName);
            Console.WriteLine(s1.GetDepID);
            Console.WriteLine(s1.GetDepName);
        }
    }
}


below is the o/p


Code Example for Abstract Class in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
    public abstract class EMP
    {
        public abstract int SALARY
        {
            get;
        }
        public string Company
        {
            get
            {
                return "ICON Training";
            }
        }
      
    }
    public class SalesEmp : EMP
    {
        public override int SALARY
        {
            get
            {
                return 2000;
            }
        }
    }
    public class TechEmp : EMP 
    {
        public override int SALARY
        {
            get
            {
                return 5000;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            SalesEmp se = new SalesEmp();
            Console.WriteLine(se.SALARY);
            TechEmp te = new TechEmp();
            Console.WriteLine(te.SALARY);
        }
    }
}

Code Example for Method Overriding /Hiding

//Method Overriding


using System;

public class Rect
{
    public virtual void getArea()
    {
        Console.WriteLine(" Rect");
    }
}

public class Square : Rect
{
    public override  void getArea()
    {
        Console.WriteLine("Square ");

    }
}
class TestClass
{
    public static void Main()
    {
        Square sq = new Square();
        Rect r = sq;
        r.getArea();
        sq.getArea();


    }
}
below 'll be the 0/p
Square
Square

//Method Hiding 
using System;
public class Rect
{
public virtual void getArea()
{
    Console.WriteLine(" Rect");
}}
public class Square:Rect
{
    public new  void getArea()
    {
        Console.WriteLine("Square ");
    
}
class TestClass
{
    public static void Main()
    {
        Square sq = new Square();
        Rect r = sq;
         r.getArea();
         sq.getArea();
      
}

below 'll be the 0/p
Rect
Square