#541 – Generic Method Type Parameters Can Hide Class-Level Type Parameters

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.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #541 – Generic Method Type Parameters Can Hide Class-Level Type Parameters

  1. Andrew says:

    sean trying to open you website to look at the awesome shed plans….it won’t open…any ideas?

    • Sean says:

      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)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: