Tuesday, 21 February 2012

What are Generics in .NET?

A little while ago, a friend of mine on Facebook asked me to explain to him what generics in .NET were. As I thought this might interest more than one friend, which it did, I decided to put it in a "note" on Facebook. That was before I started this blog, so now I decided to post it here, hopefully so that more people would find it useful.

Generics in the .NET Framework is a programming technique that allows you to create a "generic" (meaning that it's not tied to a specific type) class, structure or method. The type, which is in this case "an argument", is specified when that element is used. What's interesting, and this is another advantage of Generics in .NET, is that you can restrict that type by specifying, for example, that it has to implement a certain interface or have a parameterless constructor.

This concept allows for more type safety (the type is known when the generic element is being used), while promoting reuse (you create an element that's not tied to a specific type).

An example of Generics, which is very popular, are Generic Collections, that came with the introduction of Generics in .NET 2.0. In the earlier version of .NET (1.x), there were non-generic collections, meaning that those collections would hold "Object" types, allowing the following:

ArrayList collection = new ArrayList();
collection.Add("string");
collection.Add(1);
collection.Add(new float[10]);

This may seem to have the advantage to be "flexible" but it has many disadvantages, like having to cast the types back when retrieving them:

int i= (int) collection[1];


And you have to know which element contains which type, and that can prove to be hard. Also, cases when you would need such a collection that can hold any "Object" aren't that common.
And here come the "Generics" to the rescue. You can use, for example, the List<T> to hold objects of type "T". e.g:

List<string> stringList = new List<string>();
stringList.Add("Hello");
stringList.Add("World!");
stringList.Add(2); // this causes a compile-time error
string world = stringList[1]; // no need for the cast since the type is known

Another example of generics, other than in collections, would be something like:

int Compare<T>(T first, T second) where T:IComparable<T>
{
return first.CompareTo(second);
}

Now, this Compare method can compare any two objects (of the same type) which implement the IComparable interface (that defines the CompareTo method), which in turn makes for another good example of generics

public interface IComparable<T>
{
int CompareTo(T other);
}

Now, if you've not used generics before, maybe thinking they were hard, I hope you got a glimpse at how powerful this feature is and how useful it can be; and more importantly, how "not so hard after all" it is. So, what are you still doing here?! go make yourself some generics ;)

27 comments:

  1. I came onto your blog while focusing just slightly submits. Nice strategy for next, I will be bookmarking at once seize your complete rises... SEO company

    ReplyDelete
  2. One of the most appealing and bewitching blog that I read recently.
    augmented reality advertising

    ReplyDelete
  3. This allows them to go to class prepared. They also like using Skype, emailing their teachers instead of going to speak to them in person. They also enjoy discussion boards. wolffofcanada.com

    ReplyDelete
  4. This blog has irresistibly pleased its audience.
    jio fi

    ReplyDelete
  5. The author has done a fine job of converting the feelings into words.
    best noise cancelling headphones under 100

    ReplyDelete
  6. The blog writings were so nice, I wished they neever ended.
    www.consumerisminc.com

    ReplyDelete
  7. The return on investment will depend on whether the technologies implemented are right for a given business' needs and how prepared employees are to use them.lie detector test uk

    ReplyDelete
  8. To be able to keep yourself up to date you must come across some reliable latest technology news sources that can give you timely information

    ReplyDelete
  9. I’ve been exploring for a little for any high-quality articles or weblog posts on this kind of area . Exploring in Yahoo I finally stumbled upon this web site. Reading this information So i’m glad to express that I’ve an incredibly good uncanny feeling I discovered just what I needed. I most no doubt will make sure to don’t forget this website and give it a glance regularly. APK

    ReplyDelete
  10. This is highly informatics, crisp and clear. I think that everything has been described in systematic manner so that reader could get maximum information and learn many things.
    agenda

    ReplyDelete
  11. Hello, i think that i saw you visited my site so i came to “return the favor”.I am attempting to find things to enhance my site!I suppose its ok to use a few of your ideas!! stadtbedarf.de

    ReplyDelete
  12. The very best drones can also have some of the people top-of-the-line energy digital cameras on board as well as pass on the pictures right to rescuers using a Very first Individual Look at system.videos by a camera drone

    ReplyDelete
  13. AWS Training in Bangalore - Live Online & Classroom
    myTectra Amazon Web Services (AWS) certification training helps you to gain real time hands on experience on AWS. myTectra offers AWS training in Bangalore using classroom and AWS Online Training globally. AWS Training at myTectra delivered by the experienced professional who has atleast 4 years of relavent AWS experince and overall 8-15 years of IT experience. myTectra Offers AWS Training since 2013 and retained the positions of Top AWS Training Company in Bangalore and India.


    IOT Training in Bangalore - Live Online & Classroom
    IOT Training course observes iot as the platform for networking of different devices on the internet and their inter related communication. Reading data through the sensors and processing it with applications sitting in the cloud and thereafter passing the processed data to generate different kind of output is the motive of the complete curricula. Students are made to understand the type of input devices and communications among the devices in a wireless media.

    ReplyDelete
  14. Such a movement would coordinate the subjects of technology, social investigations, math, science, and dialect expressions with the chance to make understudy focused action.top entrepreneur movies about sales

    ReplyDelete
  15. What a fantabulous post this has been. Never seen this kind of useful post. I am grateful to you and expect more number of posts like these. Thank you very much. VPN veteran

    ReplyDelete
  16. There are things that you can do on your own to repair home appliances and they are easy to implement as well Sonos suppliers in Aberdeen

    ReplyDelete
  17. I discovered your site website on google and check a couple of your early posts. Preserve the really good operate. I merely extra encourage Feed to my MSN News Reader. Looking for forward to reading far more within you later on!… Stefan Magic

    ReplyDelete
  18. This bit of blog shows responsibility of writer.
    phone number look up

    ReplyDelete
  19. Accompanying and supporting the dramatic increases in the power and use of new information technologies has been the declining cost of communications as a result of both technological improvements and increased competition. https://tabletzap.blogspot.com/

    ReplyDelete
  20. Your blog provided us with valuable information to work with. Each & every tips of your post are awesome. Thanks a lot for sharing. Keep blogging, Read the reviews

    ReplyDelete
  21. Obviously, the first response to that question is: to satisfy the TTB (Alcohol and Tobacco Tax and Trade Bureau) regulations. https://tabletzap.blogspot.com/

    ReplyDelete
  22. Going with and supporting the sensational increments in the power and utilization of new data innovations has been the declining expense of correspondences because of both mechanical upgrades and expanded rivalry. Mr Detechtive Blog

    ReplyDelete
  23. Thanks for the tips guys. They were all great. I have been having issues with being fat both mentally and physically. Thanks to you guys i have been showing improvements. Do post more. visita il sito

    ReplyDelete
  24. Your blog provided us with valuable information to work with. Each & every tips of your post are awesome. Thanks a lot for sharing. Keep blogging, diebestenvpn

    ReplyDelete
  25. This is cool post and i enjoy to read this post. your blog is fantastic and you have good staff in your blog. nice sharing keep it up. privacy in the network

    ReplyDelete
  26. Different educationists, scientists and philosophers at different time intervals have put forwarded different definitions of Educational Technology. ASUS Rog Strix Z370-E review

    ReplyDelete