Skip to main content

Quick intro to generics

Recently ive been teaching some new developers on the team about generics, its not a new concept i know, and when you know about them you cant quite figure how people sometimes just dont know about them, they are so helpfull.

So tell me about them then!

Generics came in at .net 2.0 and are used extensively through out the .net framework internally, if you do much .net dev work you will come across then at some point.

What are generics

Generics allow you to define a type (class or structure) while leaving some of the details unspecified.

Quick Tip
When you see the following in code you know you are looking at code that uses generics

//C#
List myArray = new List();
List my2ndArray = new List();

'VB.Net
Dim myArray As New List(Of integer)();
Dim my2ndArray As New List(Of myClass)();

The main benefits for using generics are:
Type safety (you can only put ints in a collection of ints for example)
Performance (boxing and unboxing of primitive types is eliminated)
Clarity (you can see in visual studio what type of class is allowed in a generic collection, and intellisence will also help you out)

The most common (and simple) usage is in the new (as of 2.0) generic collection classes.
Previous to .net 2.0 you had ArrayList, HashTable, Queue and stack (to name just a few) these classes allow you to store collections of objects, and since every class in .net derives from object you can store any object in these classes.
So if you can store any object in a collection what the point of limiting a collection to allow it to only store objects of a certain type? The main reason is for type safety and clarity. This is best discussed by example:

ArrayList myArray = new ArrayList();
myArray.Add(1);
myArray.Add(2);
myArray.Add("3");

int counter = 0;
foreach(Object o in myArray)
{
int myInt = (int) o;
counter += myInt;
}

This code will compile fine, but will throw a runtime exception when trying to cast "3" (a string) to an int. you have to be careful when adding things to your collection and you have to make sure you handle exceptions that may arise from incorrect use. I often see code testing for the type of an object before doing a cast and if it is not of the correct type ignoring it, its bad practice, error prone, and is just unnecessary when using generics.

So if we rewrite the above example using generics:

List myArray = new List();
myArray.Add(1);
myArray.Add(2);
//myArray.Add("3"); //if uncommented will not compile

int counter = 0;
foreach(int myInt in myArray)
{
counter += myInt;
}

The change to use generic list of type int has made the code type safe (you cant add anything other than an int to myArray, if you do you will get a compile time error. Also the foreach loop is much simpler, you know that all the objects in myArray are ints, so no need for explicit type casting. All in all generic collections make the code more robust and just plain easier to read and hence maintain.

Now generics goes much deeper than just generic collections but in general you wont need to know how to create your own generic types and generic methods, but i would recommend every .net developer should know, its used all over the place. But i have not created any in any of my professional work projects.

Resources
Generics on MSDN
Use MSDN documentation on your machine
Google for Generics and .net

Facebook

Facebook Recommendations

Followers


Web Designing In Karachi



Haroof.com


Politics blogs

My Zimbio

Email Subscribe

Enter your email address:

Watch online Live TV

Popular posts from this blog

Matric General Group Result SECONDARY SCHOOL CERTIFICATE (S. S. C.) PART - II CLASS - X - 2010 (www.apnieyesp.com )

PASSED THE SECONDARY SCHOOL CERTIFICATE (S. S. C.) PART - II CLASS - X) ANNUAL EXAMINATION, 2010. ERRORS AND OMISSIONS EXCEPTED, CANDIDATES BEARING THE FOLLOWING ROLL NUMBERS ARE DECLARED TO HAVE PASSED THE SECONDARY SCHOOL CERTIFICATE (S. S. C.) PART - II CLASS - X) ANNUAL EXAMINATION, 2010. ------------------------------------------------- GENERAL GROUP (REG&PVT) --- GRADE..'A-ONE' ---- ----------------------- ( CANDIDATES SECURING TOTAL MARKS 680 AND ABOVE) MARKS SECURED BY THE CANDIDATES OUT OF TOTAL MARKS OF 850 ARE MENTIONED AGAINST EACH ROLL NUMBER IN BRACKET --------------------------------------------------- 601086 (689) XXX (XXX) XXX (XXX) XXX (XXX) XXX (XXX) XXX (XXX) 601327 (681) 363 (684) 364 (719) 407 (685) 664 (682) 788 (687) 601836 (692) 882 (683) XXX (XXX) XXX (XXX) XXX (XXX) XXX (XXX) 602315 (723) 316 (715) 320 (712) 321 (739) 325 (686) 326 (702) 602327 (683) 329 (70...

In Depth: Could robots be the writers of the future?

CNETAnalysis: It might be concerned with aliens, outer space and dimensional jumping for now, but ‘sci-fi’ might have to be redefined if the latest advances in automated writing continue apace. Software that can construct sentences, analyse data and even put a ‘spin’ on a news story are threatening to make the newsdesk and the author’s writing room very different places. The end for journalists? Journalism isn’t complicated. The popularity of online news stories can be tracked – and therefore the importance of news easily ranked – while almost everything is written using the inverted pyramid structure . Since automated writing software can already do most of that, are we looking at the last generation of human journalists? Narrative Science’s Quill is the leading automated writing software title. It transforms structured data into readable, plain English stories that are identical to those written by humans, ...

Team win: Group Health Insurance

Many small business owners know that to succeed, it must be an incentive for hiring employees who work for them. This can be any number of things, but most of the time, there is the advantage of group health insurance. This is a good strategy for small businesses for hiring new employees, there are several things you should know before you dive in choosing a plan. Before working out insurance for your business. Unable to perform Translation:invalid textA group health insurance plan may be a small business, and as few as two employees to more than fifty. There are two ways to provide health insurance for employees who are on the front line in the budget. Many small and medium enterprises, the group health insurance to contribute to the cost of the plan. On the other hand, if an employee wants to have their families, employers, the payment of staff \ 'you pay the premium and the premium for their families. Unable to perform Translation:invalid textAnother aspect of the health insuran...

Labels

Show more