.NET Tip of The Day
Learn one new .NET trick every day
Быстрое пополнение счета телефона      Login or Join

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

Comments:

ReSharper will show you when the type parameter may be omitted by displaying that portion of the text in light grey. This is true of other forms of code that are not required either (such as unused variables, methods or unreachable statements).

Drew Noakes 1/14/2008 1:10:40 PM

Name
URL
E-mail
Provide your e-mail address to receive notification about new comments.
Message
HTML tags are not supported.
Please add 7 and 1 and type the answer here:
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.