Joan Venge
Joan Venge

Reputation: 331460

Generic methods in non-generic types

When you have a method like:

public static T DoSomething<T> ( params T [ ] input )

C# lets you to call it without specifying the T, like:

DoClass.DoSomething ( "1", "2", "3" );

Does the compiler figure out T by what's passed to it?

Is this a good convention (to leave out T in this case)?

Upvotes: 3

Views: 512

Answers (4)

Reed Copsey
Reed Copsey

Reputation: 564851

As many people have mentioned, this is due to generic parameter type inference by the compiler. It discovers the type directly by the first parameter.

One other thing - if you read the design guidelines for .net libraries, it's actually recommended to write ALL of your generic methods in a way that the types can be inferred. Non-inferrable generic methods are considered more difficult to understand, and should be avoided when possible, according to the design guidelines book.

Upvotes: 1

TheSean
TheSean

Reputation: 4566

Yes, when the compiler can figure out what T is supposed to be, it is redundant to specify it. I find this a great feature, because it gets tedious and hard to read when the type name is always listed (especially with long names).

Upvotes: 1

Joe White
Joe White

Reputation: 97848

Yes, the compiler will typically figure out the type. It's called "type inference".

And yes, it's a best practice to leave T out at the call site. The less code you write, the less code someone has to read and understand later.

If you have ReSharper, it will do a good job of showing you where you can and can't get away with removing the at the call site. Otherwise you can try taking it out, and if the code compiles, then you didn't need it.

Upvotes: 1

Noldorin
Noldorin

Reputation: 147461

Yes, the compiler can infer the generic type parameter in the majority of cases. (One exceptin being when your type is a lambda expression, if I remember right.)

It is generally considered perfectly good practice to omit the generic parameters when they can be inferred. In fact, I would say that it increases readability a certain amount (specifying them is often quite redundant).

Upvotes: 3

Related Questions