Generics new features of C# 2.0

Lokesh76
Posted by in C# category on for Beginner level | Points: 250 | Views : 7925 red flag

In this article I am trying to explain all in-out about Generics.

Introduction Generics

Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. For example, by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations

Benefit of Generics types

  1. Generic allow us to create a type safe collection at compile time.
  2. Code reuseability
  3. performance
  4. by reflection we can get type information used in Generics
  5. we can also put constrained on Generics classes

How we can say Generics type safe?

So we can start with very begining menas earlier version of C# 2.0. If we want to use a List collection then what we do in code and what problem or restriction we have let go with example as

// Before C# 2.0

ArrayList objList = new ArrayList(); objList.Add(3); // Here we add int objList.Add(105); ArrayList objList2 = new ArrayList(); objList2.Add("Any String value."); objList2.Add("Any String value.");

// What we see here ArrayList allow us to store Value Type or Reference Type

So we have ArrayList and its allow us to store value and reference type both its looks cool but we need to pay some cost against type in case of error prone code, type safety, boxing, unboxing and performance as well

Let change the above code as

// Before C# 2.0

ArrayList objList = new ArrayList(); objList.Add(3); // Here we add int objList.Add(105); objList.Add("Value1"); objList.Add("Value2");

// What we see here ArrayList allow us to store Value Type or Reference Type

// Now let get the value from objList

 

int intCtr = 0; foreach (int val in objList) { intCtr += val; } // Here we get InvalidCastException exception.

Here you functionality to make heterogeneous collection with Int and String but its Error prone and error will not detected untill runtime.

Generics come into picture here to provide us type safe collection at compile time point No #1 in benefits list.

 

// C# 2.0 Generic List
List<int> objList= new List<int>();

// No

boxing, no casting:
list1.Add(3);


// If we write below line of code its show me error at compile time

 

// list1.Add("Any stirng value");


// Compile-time error:

Code reuseability

Now we are done with point of type safety and performance let come to code reuseablity. as we have one Generic collection type List<T>. As T don't denote any type so its decide type in client code at the time of declaration or instantiation. So if we want to use Int type then instantiation goes like

List<int> objList= new List<int>();
for string

List<String> objList= new List<String>();

So we have on Generic list collection and able to use any of type.

How to get type we used in Generic via reflection?

When a generic type is first constructed with a value type as a parameter, the runtime creates a specialized generic type with the supplied parameter or parameters substituted in the appropriate places in the MSIL. Specialized generic types are created once for each unique value type used as a parameter.

For example, suppose your program code declared a List constructed of integers, like this:

List<int> objList1= new List<int>();
List<int> objList2= new List<int>();

At this point, the runtime generates a specialized version of the List<T> class with the integer substituted appropriately for its parameter. Now, whenever your program code uses a list of integers, the runtime reuses the generated specialized List<T> class. In the following example, two instances of a List of integers are created, and they share a single instance of the List<int> code:

However, if at another point in your program code another List<T> class is created, this time with a different value type such as a String or a user-defined structure as its parameter, the runtime generates another version of the generic type, this time substituting a String in the appropriate places in MSIL. 

 

Conclusion

So here we go with final line as we write about very basics of Generics. We have lots of other thing also associated with Generics. I will try to add rest of thing as we get chance. specially how we can put constrained  on Generic classes.

Happy coding


Reference:  http://msdn.microsoft.com/en-us/library/f4a6ta2h.aspx

Page copy protected against web site content infringement by Copyscape

About the Author

Lokesh76
Full Name: Lokesh Kumar
Member Level: Starter
Member Status: Member
Member Since: 3/10/2011 3:42:56 AM
Country: India
Thanks Lokesh Kumar
http://www.dotnetfunda.com/lokesh_kumar

Login to vote for this post.

Comments or Responses

Posted by: Akiii on: 5/23/2011 | Points: 25
hi lokesh....

good article.......
But i have some doubts.........I am pasting the portion i didn't understand clearly....

Generics come into picture here to provide us type safe collection at compile time. Point No #1 in benefits list. 

// C# 2.0 Generic List
List<int> objList= new List<int>();

// No

boxing, no casting:
list1.Add(3);
// If we write below line of code its show me error at compile time

// list1.Add("Any string value");

// Compile-time error:


Please help me in clarifying it...

Thanks and Regards
Akiii
Posted by: Lokesh76 on: 5/23/2011 | Points: 25
Hi Akii,

There are two main points we have one is type-safe other is no casting ( we don't have casting that's means no there is no boxing or unboxing happens).

So Let us start with type-safe..
ArrayList objList = new ArrayList();

objList.Add(3); // Here we add int
objList.Add(105);

objList.Add("Value1");
objList.Add("Value2");
// What we see here ArrayList allow us to store Value Type or Reference Type // Now let get the value from objList int intCtr = 0;
foreach (int val in objList)
{
intCtr += val;
}
// Here we get InvalidCastException exception.


in above code line we are able to put any type of datatype into objList because its take every type as object. So at the time of retrival of values we are not sure about any specific datatype and getting runtime errors. but in Generics if we initilize the list with int then we are able to store any other type in it.

As in Generic its type safe so we are aware about stored type inside collection that's insure us that there is not need of casting anytime.

Login to post response

Comment using Facebook(Author doesn't get notification)