1

I was looking at the answer of stackoverflow to learn more about C# extension methods. I couldn't understand the part <T> after the method name. To be more exact:

public static bool In<T>(this T source, params T[] list)
{
  if(null==source) throw new ArgumentNullException("source");
  return list.Contains(source);
}

I can understand T refers generic name for any class. Why do we need <T> after the method name for this extension method?

Community
  • 1
  • 1
serefbilge
  • 1,654
  • 4
  • 29
  • 55
  • 2
    Otherwise it wouldn't be a generic extension method. Now you can use it with any type. Not the `T` indicates a generic type, you could also call it `TheType` if you want. – Tim Schmelter May 19 '13 at 13:14

3 Answers3

3

The T by itself doesn't mean it's generic. If you have the <> after the name, that means it's generic, with a generic parameter which you call T in this case.

public static bool In<ParameterType>(this ParameterType source, params ParameterType[] list)
{
  if(null==source) throw new ArgumentNullException("source");
  return list.Contains(source);
}
Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185
2

Because the method needs to be generic in order to operate on instances of any given type, represented by T. The <T> just tells the compiler that this method is generic with a type parameter T. If you leave it out, the compiler will treat T as an actual type, which of course for this purpose it isn't.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
1

It allows apply this extension method to any type, due to method is generic. But checking if(null==source) assumes method will work with references types. Actually, you may get NRE and I suggest to add checking for null incoming list parameter.

Uzzy
  • 550
  • 3
  • 14
  • Why should he check for `nulls`? If the list is null it will raise a `NullReferenceException` what is desired. – Tim Schmelter May 19 '13 at 13:21
  • return list.Contains(source); - if list is null he will get Null Reference exception (NRE). In method may return `false if list is null – Uzzy May 19 '13 at 13:22
  • Yes, of course. The same happens always and it is the desired behaviour if someone tries to do something with `null`. – Tim Schmelter May 19 '13 at 13:23
  • It is only suggestion to return false, instead of NRE – Uzzy May 19 '13 at 13:24