Posted by: Cirilo Meggiolaro | 04/5/2009

Tip of the day #173 – Generic type inference

Generic type inference is the ability the compiler has to infer the data type when you invoke a generic method without specify the generic type argument.

A good and simple example is demonstrated below:

private void MyGenericMethod<T>(T n1)
{ }

The method above accepts a parameter that is from the same generic type than the argument expected. You may invoke this method using the following syntax:

this.MyGenericMethod(100);

Yes, it compiles and executes properly. The condition to make this possible is to have at least one parameter from the same type than the generic argument. You cannot use the same logic based on the return type of a method. Take a look on the snippet below:

private T MyGenericMethod<T>()
{
    return default(T);
}

You will not be able to invoke this method using the following syntax:

int n = MyGenericMethod(); // Compiler error


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

Categories

%d bloggers like this: