.NET Tip of The Day
Learn one new .NET trick every day
Login or Join
.NET Tips & Tricks Community RSS

Those who prefer reading this site through RSS now can also subscribe for updates to .NET Tips & Tricks Community.

Simplify the usability of your generic methods with type parameter inference

When the parameter signature of a generic method includes a parameter that is of the same type as the type parameter for the method, it's not necessary to specify the type parameter when calling the method. Let's review an example:

    public class Class1

    {

        //both method type argument and parameter are of the same type

        public void SomeGenericMethod<T>(T sameAsTypeParameter)

        {

            ...

        }

    }

 

    public class Test

    {

        static void Main()

        {

            Class1 obj = new Class1();

            //It's not necessary to specify method type parameter

            //Instead of obj.SomeGenericMethod<int>(100) use

            obj.SomeGenericMethod(100);

        }

    }

As you can see in the example above, the syntax for calling generic method is identical to syntax of calling non-generic method. This ability is called generic type inference. To enable inference, the parameter signature of a generic method must include a parameter that is of the same type as the type parameter for the method.

Note: the compiler cannot infer the type based on the type of the returned value alone.

11/20/2007
RSS .NET Tip of The Day
Subscribe to receive one tip from the .NET Tips and Tricks Community per day.
Previous Tips of The Day
The best of the .NET Tips & Tricks Community.
.NET Practitioners .NET Tips & Tricks Community
Every .NET practitioner has a trick up in their sleeve. This is the place to share it with other .NET people.
Submit a Tip
Discovered a new trick? Share it with others.
My Tips
Manage tips you authored.