#541 – Generic Method Type Parameters Can Hide Class-Level Type Parameters
March 16, 2012 2 Comments
When you have generic methods within a generic class, if the name of a type parameter in the generic method matches the name of a type parameter for the class, the parameter in the method takes precedence.
In the example below, both the Dog class and the BuryThing method declare a type parameter named T. Within the body of the BuryThing method, the method’s type parameter is used, rather than the class-level type parameter of the same name.
public class Dog<T> { // This method's type parameter hides the class-level type parameter public void BuryThing<T>(T thing) { Console.WriteLine("T's type is {0}", typeof(T).ToString()); }
Dog<Cow> d = new Dog<Cow>("Buster", 5); d.BuryThing(new Bone("Rawhide"));
To avoid this confusion, you should give your type parameters meaningful names, e.g. TDogThing and TThingToBury.
sean trying to open you website to look at the awesome shed plans….it won’t open…any ideas?
Thanks (awesome). The server will be down for a few days. A workman inadvertently kicked it off the shelf and it’s totaled. So I’ll be rebuilding it this weekend. :O)