Geeks With Blogs
Tanveer Ibn Haresh

 

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

Posted on Monday, March 23, 2009 2:09 PM C# | Back to top


Comments on this post: FootNotes on C# Generics

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

Great educational post, I learned so much about it

Anyway, thanks for the post
Left by web development company on Aug 19, 2009 1:03 PM

# re: FootNotes on C# Generics
Requesting 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 Oct 08, 2009 2:56 PM

# re: FootNotes on C# Generics
Requesting Gravatar...
I learned so much about it too!thinks!
Left by replica shoes on Oct 22, 2009 9:59 PM

# re: FootNotes on C# Generics
Requesting Gravatar...
thank you for sharing knowledge
Left by led lights on Dec 10, 2009 3:02 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
nice, thans for sharing
Left by Casino online bonus on Jan 03, 2010 11:28 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
nice, thans for sharing it
Left by Casino online on Jan 03, 2010 11:30 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
nice thank you
Left by gratta e Vinci on Jan 03, 2010 11:32 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
wow nice post
Left by bingo on Jan 03, 2010 11:33 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
thanks again.
Left by iphone fix on Mar 09, 2010 9:39 PM

# re: FootNotes on C# Generics
Requesting 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 Mar 23, 2010 4:49 AM

# re: FootNotes on C# Generics
Requesting 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 Mar 26, 2010 12:22 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
It is extremely helpful and beneficial.

Thanks a lot.
Left by disney restaurants on Mar 31, 2010 3:38 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
Great!It is very nice.Thank you for the post.
Left by replica on Apr 05, 2010 2:07 AM

# re: FootNotes on C# Generics
Requesting 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 Apr 13, 2010 2:20 PM

# re: FootNotes on C# Generics
Requesting Gravatar...
Your article give me more inspriration to do that... thanks for sharing... Keep posting article like that.
Left by halibut fishing on Apr 28, 2010 9:33 PM

# re: FootNotes on C# Generics
Requesting Gravatar...
You have no idea how much time this saved me. Thanks for the tutorial - bookmarked.
Left by Free iPod on Jun 15, 2010 3:10 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
It quite confusing for me for beginning. But i will try
Left by zach on Jun 22, 2010 3:45 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
its useful.
thnx sharing.
Left by Revitol Dermasis on Jun 23, 2010 10:12 PM

# re: FootNotes on C# Generics
Requesting Gravatar...
Great educational post, I learned so much about it.
Left by Pandora Beads on Jun 24, 2010 8:55 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
It is very useful.
Thanks for sharing.
Left by Promotional Products on Jun 24, 2010 9:01 AM

# wsi
Requesting 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 Jul 09, 2010 9:20 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
Thank you so much for this valuable information. Very useful indeed
Left by keputihan on Jul 19, 2010 11:05 PM

# re: FootNotes on C# Generics
Requesting 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 Jul 30, 2010 1:10 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
This is an amazing postor read ! i never seen that before ! i love your blog!
Left by stock market today on Aug 01, 2010 9:20 PM

# re: FootNotes on C# Generics
Requesting Gravatar...
It is very useful.
Thanks for sharing.
Left by Louis vuitton outlet on Aug 10, 2010 11:45 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
This is an amazing postor read ! i never seen that before !
Left by Chanel bags on Aug 10, 2010 11:46 AM

# re: FootNotes on C# Generics
Requesting 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 Aug 25, 2010 9:57 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
awesome tips!
Left by almendes on Sep 06, 2010 10:20 PM

# re: FootNotes on C# Generics
Requesting Gravatar...
i love this post! learning will become easier.
Left by gabby pierzon on Sep 06, 2010 10:21 PM

# re: FootNotes on C# Generics
Requesting Gravatar...
Thanks for sharing.
Left by Botswana safari on Sep 07, 2010 5:13 AM

# re: FootNotes on C# Generics
Requesting 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 Sep 08, 2010 6:58 AM

# re: FootNotes on C# Generics
Requesting 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 Sep 16, 2010 2:37 AM

# re: FootNotes on C# Generics
Requesting 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 Sep 16, 2010 2:40 AM

# re: FootNotes on C# Generics
Requesting 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 Sep 20, 2010 3:56 AM

# Mr
Requesting 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 Oct 26, 2010 2:56 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
i nevwe come across such an intrusive work...thanks for sharing
Left by brandy on Nov 03, 2010 12:37 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
Thanks for sharing this valuable post. Hope it helps many friends.
Left by Chicken Houses on Nov 10, 2010 8:07 AM

# Mr
Requesting 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 Nov 26, 2010 7:49 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
Thanks for the post. Interesting indeed.
Left by Losing Stomach Fat on Dec 04, 2010 6:28 PM

# re: FootNotes on C# Generics
Requesting 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 Jan 08, 2011 1:00 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
Great sharing! Thank you for this post
Left by alex on Jan 11, 2011 9:52 PM

# re: FootNotes on C# Generics
Requesting Gravatar...
I would say myspace because its easy and your friends can help you get your music around.
Left by Zambia Safari on Jan 21, 2011 1:50 AM

# re: FootNotes on C# Generics
Requesting 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 Feb 03, 2011 3:22 PM

# re: FootNotes on C# Generics
Requesting 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 Feb 03, 2011 7:35 PM

# re: FootNotes on C# Generics
Requesting 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 Feb 06, 2011 11:33 AM

# re: FootNotes on C# Generics
Requesting 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 Feb 07, 2011 9:14 AM

# re: FootNotes on C# Generics
Requesting 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 Feb 09, 2011 3:58 AM

# re: FootNotes on C# Generics
Requesting 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 Feb 14, 2011 4:37 AM

# re: FootNotes on C# Generics
Requesting 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 Feb 14, 2011 8:32 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
Max method is not recommended.
Left by qlwik on Feb 16, 2011 8:30 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
Learning a lot from your posts. Great job!
Left by Canine Lymphoma Treatment on Mar 10, 2011 6:31 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
Thank you for the clear explanation.
Left by Diet Tea on Mar 10, 2011 6:40 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
This adds to my learning of C#.
Left by Meratol on Mar 10, 2011 6:51 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
Looking forward to more educational posts from you.
Left by How to lose belly fat fast on Mar 10, 2011 7:07 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
Thank you for sharing this info.T
Left by Shih Tzu Training on Mar 10, 2011 8:32 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
Learning to work in C# is a long process. Every tutorial is useful. Thanks
Left by lower stomach exercises on Mar 21, 2011 4:25 PM

# re: FootNotes on C# Generics
Requesting Gravatar...
Thank you for sharing this info.T
Left by vintage wedding invitations on Mar 23, 2011 1:40 AM

# Tanzania Safari
Requesting Gravatar...
This post is so great and i have bookmarked the site.
Left by Andrew Tanzania on Mar 23, 2011 6:36 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
Looking forward to educational posts from you.
Left by pandora beads on Mar 24, 2011 10:14 PM

# re: FootNotes on C# Generics
Requesting Gravatar...
Thanks for sharing how to change the generic method declaration to get the results you want.
Left by buy proactol on Apr 07, 2011 11:46 AM

# re: FootNotes on C# Generics
Requesting Gravatar...
Thanks,... this is a good article for getting ideas on the utility of generics..

i will need some more practice to understand clearly about the situations where generics are better than inherited classes.

Thanks for taking such great efforts to help others understand !

something i noticed in the post -

There are two places where you use the statement
“A derived class inherits a base class, but a collection of derived class, doesn’t inherit a collection of base class”.

I think that rule is valid only in the second instance( second point )..

In the first instance, the example -
'......
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){}
..
..'

In the first instance, the flaw with Inheritance might be stated as -
"Derived classes can expose the same type as their Parent through inherited methods, whereas it might be preferred to expose their own type using such methods".......... or something like that

Left by phab on Feb 24, 2012 6:17 AM

Your comment:
 (will show your gravatar)
 


Copyright © Tanveer-Ibn-Haresh | Powered by: GeeksWithBlogs.net | Join free