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 ;)

45 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. 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
  14. 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
  15. 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
  16. 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
  17. This bit of blog shows responsibility of writer.
    phone number look up

    ReplyDelete
  18. 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
  19. 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
  20. 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
  21. 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
  22. 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
  23. 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
  24. Different educationists, scientists and philosophers at different time intervals have put forwarded different definitions of Educational Technology. ASUS Rog Strix Z370-E review

    ReplyDelete
  25. I have to convey my respect for your kindness for all those that require guidance on this one field. Your special commitment to passing the solution up and down has been incredibly functional and has continually empowered most people just like me to achieve their dreams. Your amazing insightful information entails much to me and especially to my peers. Thanks a ton; from all of us. showbox apk

    ReplyDelete
  26. I would like to say that this blog really convinced me to do it! Thanks, very good post. ad network examples

    ReplyDelete
  27. Good post. I be taught something more difficult on totally different blogs everyday. It should always be stimulating to read content from other writers and observe a little bit one thing from their store. I’d prefer to use some with the content on my weblog whether or not you don’t mind. Natually I’ll give you a link in your net blog. Thanks for sharing. security 

    ReplyDelete
  28. Laser cutting machines are likewise being utilized today in shockingly low tech applications too. For example, think about the issues in material assembling.best laser cutting machine

    ReplyDelete
  29. The tone is so powerful and conceivable.
    Mason Soiza

    ReplyDelete
  30. Your website is really cool and this is a great inspiring article. Thank you so much.
    Mason Soiza

    ReplyDelete
  31. Hey there ~ Great stuff, will definitely come back very soon! PLC programming

    ReplyDelete
  32. The both of us really enjoyed your post. It appears like you’ve put a lot of effort into your story and the human race need much more of these on the Net these days. I do not real have a large deal to say in retort, I just wanted to comment to tell well done. marvelous post. i never thought of that. Free Calls Online Without Registration

    ReplyDelete
  33. Both Augmented Reality (AR) and Virtual Reality (VR) and have taken the amusement and gaming industry by tempest. Nothing can stop AR technology in versatile applications to increase new energy in 2018.
    https://www.techpally.com/special-guest-app/

    ReplyDelete
  34. Introduce a robber alert framework that can stop any criminal in his tracks. Keep your most valuable resources and assets secured up a safe.

    Witty Spy

    ReplyDelete
  35. Computer-assisted Instruction (CAI) used for education since 1950s also became popular during this era.used test equipment for sale

    ReplyDelete
  36. On the other hand, if you are overrun with mice then the opportunity exists to innovate a product using your technology.how to disable internet explorer

    ReplyDelete
  37. i have entre most of the articles re your website now, and i basically following your fashion of running a blog. I bonus it to my favorites weblog web page list and might be checking sponsorship soon. Please test out my web site as ably and take me know what you think. TNF Dubai

    ReplyDelete
  38. I wish more authors of this type of content would take the time you did to research and write so well. I am very impressed with your vision and insight. diadiktiokaiasfalia

    ReplyDelete
  39. Interesting post. I Have Been wondering about this issue. so thanks for posting. Pretty cool post.It 's really very nice and Useful post.Thanks Mehr Informationen

    ReplyDelete
  40. On the off chance that you can deal with that, at that point the open doors for progress are practically boundless. https://techeries.com/

    ReplyDelete
  41. Along these lines the family can get paid for extra power created, and can likewise obtain power around evening time. Zonnepanelen Kopen bij Installateur Soloya

    ReplyDelete
  42. This comment has been removed by the author.

    ReplyDelete
  43. This can be accomplished by adding more protection to your rooftop, or introducing an additional south-bound window. Zonnepanelen

    ReplyDelete
  44. When your website or blog goes live for the first time, it is exciting. That is until you realize no one but you and your. Hindistan-İşletme-Vizesi

    ReplyDelete
  45. Thank you very much for writing such an interesting article on this topic. This has really made me think and I hope to read more. 印度緊急簽證

    ReplyDelete