Most Viewed

Most Viewed

Thursday 7 June 2012

C# Generics Introduction & Interview Questions


C# Generics Introduction


•Generics are similar to C++ templates
•Generics offers performance and type safety
•Generics for defining placeholders (type parameters) for method arguments and type definitions, which are specified at the time of invoking the generic method or creating the generic type.
•Boxing and unboxing is under the control of CLR which is implemented at runtime which is overhead  and reduce performance.
     ArrayList al = new ArrayList();    al.Add(10);
    console.WriteLine(“value :”+(int)al[0];
  -   Observe box and unbox opcode in 

   CIL»In Collections, adding a value types to a collection results in boxing and unboxing when the value type is converted to a reference type and vice versa.

     Instead of using objects, the List<T> class from the namespace System.Collections.Generic allows you to define the type when it is used.
    
    »The generic type of the List<t> class is defined as int, and so the int type is used inside the class that is generated dynamically from the JIT compiler. No boxing and unboxing required.
     
    <int> l = new List<int>();
    l.Add(100);  // no boxing 
    int i1= l[0];  // no unboxing
    foreach(int i2 in l)   
     { 
       Console.WriteLine(i2);
     }
    

    »Error should be detected as early as possible (compile time).

    »Compiler does not compile if you say
     
       List<int> l = new List<int>)();
       l.Add(“string”); // compile time error.

•The Problem with (un)Boxing Operations
–A new object must be allocated on the managed heap
–The value of the stack-based data must be  transferred into that memory location
–When unboxed, the value stored on the heap-based object must be transferred back to the stack.
–The new unused object object on the heap will  be garbage collected.
–This is performance issue
–Console.WriteLine(“Value”+(short)al[0]); 
throws InvalidCastException.
.Net 2.0 is solution  to above problems.


 

*System.Collections.Generic namespace  contains interfaces and classes for generics.
–ICollection<T>
–IComparer <T>
–Idictionary<K,V>
–IEnumerator<T>
–IList<T>



*Examine the List<T> type:

–Generic classes are heap-allocated objects and therefore new-ed with any required  constructor arguments.
–System.Collections.Generic.List<T> requires you to specify a single value that describes the type of item the List<T> will operate upon.

Create a list containing  integers             
–List<int> l = new List<int>()
–List<Emp>  e= new List<Emp>();
–e.Add(new Emp());
-Generic Methods
-Omission of Type Parametes
-Creating Generic Structures ( or classes)
-The default Keyword in Generic Code
-Generic Interface
-Generic Delegates
-Generic Events
-Custom generic Collections


-Generics effectively used  in Web Service,WCF and WF of  
            .net 2.0/3.5/4.0

Interview Questions in C#.Net Generics

 

No comments:

Post a Comment