Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic methods in non-generic types

Tags:

c#

.net

generics

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)?

like image 779
Joan Venge Avatar asked Jan 02 '26 06:01

Joan Venge


1 Answers

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).

like image 198
Noldorin Avatar answered Jan 03 '26 18:01

Noldorin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!