سؤال

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?

هل كانت مفيدة؟

المحلول 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.

نصائح أخرى

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);
}

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top