FootNotes on C# Generics

 

To declare a list of  objects  of type T

List<T> list=new List<T>();

Here T is a parametric Type. You can use any data type  or class in place of the T.

List<int> list=new List<int>();

Here, List is a collection of objects of type integer.

Now if you write..

list.add(1);

list.add(2);

It will execute successfully .But if you just write

list.add(3.0);

It will throw a runtime exception because 3.0 is not of integer type and the generic list has been declared as type integer.

This is how you declare a generic type class:

public class FirstList<T>

{

}

So T  acts as a constructor parameter, which defines the type for the generic. Some interesting facts about the execution cycle of generics should be discussed here.

If you declare and instantiate MyList Like bellow:

FirstList<int> list1=new FirstList<int>();

FirstList<int> list2=new FirstList<int>();

Firstlist<double>  list3=new FirstList<double>();

Normal situation suggests that we have only one class there with 3 instances. But if we dig deep we will find out that there are two classes here . FirstList[System.Int32]   which has 2 instances and FirstList[System.Double], which has one instance. Interesting thing is that , in IL level, there is only one class FirstList<T>.So where does these 2 classes come from? When are they created. Interesting to know that the instances of these two types of classes are created in runtime by the CLR when the code is loaded in the memory. That gives the system a great performance overhead. So the classes are only created when they are needed, which is a very efficient way of programming.

Now lets talk about Generic methods.

public T Max<T>(T val1, T val2) where T : IComparable  {

    T FinalVal = val2;

    if (val2.CompareTo(val1) < 0)

        FinalVal = val1;

    return FinalVal;

   }

The method here is called Max and it has become a parameterized type. It accepts a type parameter, which is the signature for any Generic method. So whatever type you pass on in the type parameter, can be referenced within the method. Note that as it is declared as Type T, the return type of the function will be also of that parameterized type. Look at the second part of the function declaration. The ‘where’ section shows how to implement constraints on the Generic methods. By constraint here, we say the compiler that, the parametric type T has to implement the IComparable interface.

“A derived class inherits a base class, but a collection of derived class, doesn’t inherit a collection of base class”.

Lets say we have 3 classes like these:

class Furniture{}

class Table{}:Furniture{}

class Chair{}:Furniture{}

Suppose we have a method in Furniture class.

static void Make(Furniture f){}

Here if we pass a table or chair object, that would also compile successfully.

Make(Table t);

Make(Chair c);

If we override the Make method in the derived class Table as:

public override Make(Furniture F)

{

         base.Make(F);

}

There is a problem, we can even pass an object  of class Chair  in this method. So a Table class can even make a Chair.Many programmers would not want that to happen. Here comes the use of generics.

“A derived class inherits a base class, but a collection of derived class, doesn’t inherit a collection of base class”.

Lets  say we have a method

static void Make(FirstList<Furniture>  furniture){}

So if we invoke the method as

Make(new FirstList<Furniture>  furniture);

It would compile successfully. But if we try something like this

Make(new FirstList<Table> table);

It will raise a compile time error. Why? Because a object of Table class do inherit  base class Furniture, but a list or collection of Table objects do not inherit a list or collection of Furniture class.

Lets  see this example:

class Furniture

{

public  virtual  void Paint(FirstList<Furniture> furnitures ) {}

}

public class  Table:Furniture

{

public  override  void Paint(FirstList<Furniture> furnitures ) {}

}

public class  Chair:Furniture

{

public  override  void Paint(FirstList<Furniture> furnitures ) {}

}

 

Now if we test the new classes.

class  Program

{

                Static void Main(string[] args)

                {

Table table=new Table();

Table.Paint(new FirstList<Furniture>());

Table.Paint(new FirstList<Table>());

}

}

If we execute this code, the first 2 lines will execute, but it would raise error in the 3rd line. Why? The Table class can’t even Paint its on instance. Table is a child class of Furniture and there might be some situations where we would like that the table class has  the capability to paint Chair objects also. How would  we establish that?

Lets make some improvements in our classes. Make the methods generic methods. Lets change all the 3 Paint methods with this new one.

public  override  void Paint<T>(FirstList<T> furnitures ) {}

So now we will see if we execute

Table.Paint(new FirstList<Table>());

Table.Paint(new FirstLIst<Chair>());

Both these lines will execute successfully. Oh, good work? Well, isn’t there a glitch? Let us run this..

Table.Paint(new FIrstList<Program>());

Oops, it is executing without any error. Should we let that happen? Shouldn’t we make sure that it can only pain derived classes of the Furniture. So lets do it.

What we have to do here is to put a constraint in the method declaration of the base class that is Furniture. Lets do it like this.

public  override  void Paint<T>(FirstList<T> furnitures ) where T : Furniture

 {}

So we are making sure here that  any type passed in the parameterized type variable T is indeed a derived class of base class that is Furniture here. Remember that putting this constraint only in the base class would be enough, we don’t have to repeat it in the child classes again.

 

Now lets make some changes in our generic class.

public class FirstList<T>

{

public  void  Insert(T obj)

{

}

public  void  Push (()

{

                Insert(new T());

}

}

 

Now if we compile this, we would get an error. In the line add(new T()). That is because T is a generic  parameter Type and remember that all classes do not have a parameterless constructor. So to make it work we will have to add a constraint in the class declaration.

public class FirstList<T> where T : new()

{

………...

}

So it defines that any type passed as the parameter type in the class would have to have a parameterless constructor.

So if you  modify the class furniture like this

class Furniture

{

public  virtual  void Paint<T>(FirstList<T> furnitures ) {}  where T:  Furniture

}

In this case we would get an error here.

“'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'ConsoleApplication1.MyList<T>'”

This is happening because FirstList  as a generic type expects the type parameter to have parameterless constructor. So if we change the generic method declaration as

public  virtual  void Paint<T>(FirstList<T> furnitures ) {}  where T:  Furniture,new()

Our problem will be solved.

 

 Inspired by Presentation on www.dnrTv.com

61 Comments Filed Under [ C# ]
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Comments

# re: FootNotes on C# Generics
Gravatar Nice post,

Great educational post, I learned so much about it

Anyway, thanks for the post
Left by web development company on 8/19/2009 1:03 PM
# re: FootNotes on C# Generics
Gravatar List of objects is interest feature of C#. I have 2 year experience in programming on C# but I've never heard about it.
Left by Dan Fire on 10/8/2009 2:56 PM
# re: FootNotes on C# Generics
Gravatar I learned so much about it too!thinks!
Left by replica shoes on 10/22/2009 9:59 PM
# re: FootNotes on C# Generics
Gravatar thank you for sharing knowledge
Left by led lights on 12/10/2009 3:02 AM
# re: FootNotes on C# Generics
Gravatar nice, thans for sharing
Left by Casino online bonus on 1/3/2010 11:28 AM
# re: FootNotes on C# Generics
Gravatar nice, thans for sharing it
Left by Casino online on 1/3/2010 11:30 AM
# re: FootNotes on C# Generics
Gravatar nice thank you
Left by gratta e Vinci on 1/3/2010 11:32 AM
# re: FootNotes on C# Generics
Gravatar wow nice post
Left by bingo on 1/3/2010 11:33 AM
# re: FootNotes on C# Generics
Gravatar thanks again.
Left by iphone fix on 3/9/2010 9:39 PM
# re: FootNotes on C# Generics
Gravatar Thank you for another great article. Where else could anyone get that kind of information in such a perfect way of writing? I have a presentation next week, and I am on the look for such information.
Left by Adult VOD on 3/23/2010 4:49 AM
# re: FootNotes on C# Generics
Gravatar I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful and beneficial to your readers Nice article..
Left by Kasino Rezensionen on 3/26/2010 12:22 AM
# re: FootNotes on C# Generics
Gravatar It is extremely helpful and beneficial.

Thanks a lot.
Left by disney restaurants on 3/31/2010 3:38 AM
# re: FootNotes on C# Generics
Gravatar Great!It is very nice.Thank you for the post.
Left by replica on 4/5/2010 2:07 AM
# re: FootNotes on C# Generics
Gravatar Wow, I really think that instead management, I should have picked career as a c plus programmer, I think I like that better.
Left by Losing belly on 4/13/2010 2:20 PM
# re: FootNotes on C# Generics
Gravatar Your article give me more inspriration to do that... thanks for sharing... Keep posting article like that.
Left by halibut fishing on 4/28/2010 9:33 PM
# re: FootNotes on C# Generics
Gravatar You have no idea how much time this saved me. Thanks for the tutorial - bookmarked.
Left by Free iPod on 6/15/2010 3:10 AM
# re: FootNotes on C# Generics
Gravatar nice info..
Left by http://www.namecandy.com/name-la on 6/22/2010 3:04 AM
# re: FootNotes on C# Generics
Gravatar It quite confusing for me for beginning. But i will try
Left by zach on 6/22/2010 3:45 AM
# re: FootNotes on C# Generics
Gravatar its useful.
thnx sharing.
Left by Revitol Dermasis on 6/23/2010 10:12 PM
# re: FootNotes on C# Generics
Gravatar Great educational post, I learned so much about it.
Left by Pandora Beads on 6/24/2010 8:55 AM
# re: FootNotes on C# Generics
Gravatar It is very useful.
Thanks for sharing.
Left by Promotional Products on 6/24/2010 9:01 AM
# wsi
Gravatar Your WSI Consultant can give you an interactive demonstration on how improving conversion translates into more profit. And we’ll always be available to answer questions, and offer recommendations to ensure you’re always getting a maximum return on your Internet investment.
Left by Seo Consultant Hertfordshrie on 7/9/2010 9:20 AM
# re: FootNotes on C# Generics
Gravatar Thank you so much for this valuable information. Very useful indeed
Left by keputihan on 7/19/2010 11:05 PM
# re: FootNotes on C# Generics
Gravatar That is a good business, at leat it sounds to be so. Hope the prospect is really that good. I wish you the best. Steam showers
Left by Steam Showers on 7/30/2010 1:10 AM
# re: FootNotes on C# Generics
Gravatar This is an amazing postor read ! i never seen that before ! i love your blog!
Left by stock market today on 8/1/2010 9:20 PM
# re: FootNotes on C# Generics
Gravatar It is very useful.
Thanks for sharing.
Left by Louis vuitton outlet on 8/10/2010 11:45 AM
# re: FootNotes on C# Generics
Gravatar This is an amazing postor read ! i never seen that before !
Left by Chanel bags on 8/10/2010 11:46 AM
# re: FootNotes on C# Generics
Gravatar Branded one's are assured of high quality standards. generics are from company of less reputation. If you buy branded one's you are very sure that what it says in the phamplet is true like correct dosing without any alteration.
Left by broken iPhone on 8/25/2010 9:57 AM
# re: FootNotes on C# Generics
Gravatar awesome tips!
Left by almendes on 9/6/2010 10:20 PM
# re: FootNotes on C# Generics
Gravatar i love this post! learning will become easier.
Left by gabby pierzon on 9/6/2010 10:21 PM
# re: FootNotes on C# Generics
Gravatar Thanks for sharing.
Left by Botswana safari on 9/7/2010 5:13 AM
# re: FootNotes on C# Generics
Gravatar Unless a doctor has written "dispense as written" or "do not substitute" a patient may request, or a pharmacist may suggest that a generic may be substituted. At least that is the case in the state where I practiced.
Left by Business Gifts on 9/8/2010 6:58 AM
# re: FootNotes on C# Generics
Gravatar Branded one's are assured of high quality standards. generics are from company of less reputation. If you buy branded one's you are very sure that what it says in the phamplet is true like correct dosing without any alteration.
Left by Whole Life Insurance on 9/16/2010 2:37 AM
# re: FootNotes on C# Generics
Gravatar Marketing science knows how to make doctors prescribe a certain brand! And in many cases, its just the doctors personal idea to prescribe a specific brand. And in many other cases, different brands of the same drug are different in formulations, which makes it more effective or less effective for certain patients.
Left by Whole Life Insurance on 9/16/2010 2:40 AM
# re: FootNotes on C# Generics
Gravatar The generic brand is pretty much the same thing, but it's not a name brand. You know the ingredients list? That might be a way they now. Or else studies. I'm not really sure.
Left by life extension treatments on 9/20/2010 3:56 AM
# Mr
Gravatar There is no "War", more like a massacre... It's Rocks, Ak-47's and ROckets vs. Tanks, Helicopter Gun ships, Naval battle ships, F-16's, APC's and much more.... I would hardly call that a war.
Left by Toronto Windshield Replacement on 10/26/2010 2:56 AM
# re: FootNotes on C# Generics
Gravatar i nevwe come across such an intrusive work...thanks for sharing
Left by brandy on 11/3/2010 12:37 AM
# re: FootNotes on C# Generics
Gravatar Thanks for sharing this valuable post. Hope it helps many friends.
Left by Chicken Houses on 11/10/2010 8:07 AM
# Mr
Gravatar I believe this particular problem has been resolved since my retirement. In pediatrics we prescribe many drugs in liquid forms. Some brands of antibiotics taste much better than generics. It's no saving if a small child refuses a bad tasting generic.
Left by hermes birkin on 11/26/2010 7:49 AM
# re: FootNotes on C# Generics
Gravatar Thanks for the post. Interesting indeed.
Left by Losing Stomach Fat on 12/4/2010 6:28 PM
# re: FootNotes on C# Generics
Gravatar when u go on a trip to africs, do u enter McDonal or some local restuarnt, when both are side by side. i bet most f those who are aquianted with Mc enters inside their golder arches.
Left by Gucci Replica on 1/8/2011 1:00 AM
# re: FootNotes on C# Generics
Gravatar Great sharing! Thank you for this post
Left by alex on 1/11/2011 9:52 PM
# re: FootNotes on C# Generics
Gravatar I would say myspace because its easy and your friends can help you get your music around.
Left by Zambia Safari on 1/21/2011 1:50 AM
# re: FootNotes on C# Generics
Gravatar This is a very confusing topic but you did a good job of explaining it clearly. Thanks for putting the effort into it for us!
Left by Panic Cure Review on 2/3/2011 3:22 PM
# re: FootNotes on C# Generics
Gravatar This is a very confusing topic but you did a good job of explaining it clearly. Thanks for putting the effort into it for us!
Left by Panic Away Review on 2/3/2011 7:35 PM
# re: FootNotes on C# Generics
Gravatar Very good points you wrote here..Great stuff...I think you've made some truly interesting points.Keep up the good work.
Left by free newsletter templates on 2/6/2011 11:33 AM
# re: FootNotes on C# Generics
Gravatar I am very enjoyed for this blog. Its an informative topic. It help me very much to solve some problems. Its opportunity are so fantastic and working style so speedy. I think it may be help all of you. Thanks a lot for enjoying this beauty blog with me. I am appreciating it very much! Looking forward to another great blog. Good luck to the author! all the best!
Left by pajama jeans on 2/7/2011 9:14 AM
# re: FootNotes on C# Generics
Gravatar You certainly have some agreeable opinions and views. Your blog provides a fresh look at the subject. Thanks for spending the time to discuss this. I believe your forthcoming articles will turn out to be just as helpful.
Left by casinos on 2/9/2011 3:58 AM
# re: FootNotes on C# Generics
Gravatar Interesting post and thanks for sharing. Some things in here I have not thought about before.Thanks for making such a cool post which is really very well written.will be referring a lot of friends about this.Keep blogging
Left by pillow pets on 2/14/2011 4:37 AM
# re: FootNotes on C# Generics
Gravatar Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.
Left by new york divorce lawyer on 2/14/2011 8:32 AM
# re: FootNotes on C# Generics
Gravatar Max method is not recommended.
Left by qlwik on 2/16/2011 8:30 AM
# re: FootNotes on C# Generics
Gravatar Learning a lot from your posts. Great job!
Left by Canine Lymphoma Treatment on 3/10/2011 6:31 AM
# re: FootNotes on C# Generics
Gravatar Thank you for the clear explanation.
Left by Diet Tea on 3/10/2011 6:40 AM
# re: FootNotes on C# Generics
Gravatar This adds to my learning of C#.
Left by Meratol on 3/10/2011 6:51 AM
# re: FootNotes on C# Generics
Gravatar Looking forward to more educational posts from you.
Left by How to lose belly fat fast on 3/10/2011 7:07 AM
# re: FootNotes on C# Generics
Gravatar Thank you for sharing this info.T
Left by Shih Tzu Training on 3/10/2011 8:32 AM
# re: FootNotes on C# Generics
Gravatar Learning to work in C# is a long process. Every tutorial is useful. Thanks
Left by lower stomach exercises on 3/21/2011 4:25 PM
# re: FootNotes on C# Generics
Gravatar Thank you for sharing this info.T
Left by vintage wedding invitations on 3/23/2011 1:40 AM
# Tanzania Safari
Gravatar This post is so great and i have bookmarked the site.
Left by Andrew Tanzania on 3/23/2011 6:36 AM
# re: FootNotes on C# Generics
Gravatar Looking forward to educational posts from you.
Left by pandora beads on 3/24/2011 10:14 PM
# re: FootNotes on C# Generics
Gravatar Thanks for sharing how to change the generic method declaration to get the results you want.
Left by buy proactol on 4/7/2011 11:46 AM

Leave Your Comment

Title*
Name*
Email (never displayed)
 (will show your gravatar)
Url
Comment*

 

Preview Your Comment.