Pages

Thursday, May 23, 2013

Generics in c#

* Generic in c# gives reusability.
*Generic are equivalent to templet in c#.
*By using generic collection we can avoid boxing ,unboxing and casting conversion.
*Generic provide type safety.

i.Dictionary(key,Tvalue)
ii.list(Tkey)
iii.Queue(Tkey)
iv.stack(Tkey)
v.linkedlist<T>
vi.Hashset
vii.SortedDictionary<Tkey,Tvalue>

*All generic collection classes are present in "system.collection" generic name space

Sample code:

{
  B b =new B();
  A<int> a =new A<int>();
  A<float> a =new A<float>();
}

How to create object in generic class?

Ans:
public class D(T1,T2)
{
   D<int, int> d1=new D<int ,int>();
  }

How to create multiple signature declare in generic class?

Ans:
public class E<T1,T2,T3,T4>
  {
   D<int ,int,int,int> d1=new D<int,int,int,int>
}

Sample code2:

public class Test
{
  protected void page-load(-,-)
  {
   G<int> g1=new G<int>();
   int x1=g1.m(10);
   G<string> g2=new G<string>();
   string s2=g2.m("hello");
  }
}
public class G<T>
  {
    public T M(T t)
    {
     return t;
   }
public string m(string t)
  {
    return t;
   }
public int m(int t)
  {
   return t;
 }
}

NOTE:

By using generic  collection classes we can avoid all the problem present in normal collection classes(boxing.unboxing) or casting converstion.

 Example:
 {
  List<int> 1st salary =new list<int>();
  1st salary.Add(1000);
1st salary.Add(2000);
1st salary.Add(3000);
1st salary.Add(4000);
foreach(int i in 1st salary)
  {
   Response.write(i);
   }
}

How to create Method in generic class?

Ans:
{
  Apple a=new Apple();
  int r1=a.Add<int>(10);
  string s1=a.Add<string>("mango") ;
  }
}
Public class Apple
{
  public T Add<T>(T t1)    // generic method
  {
    return t;
   }
}


No comments:

Post a Comment