I’m a bit confused about why/when I’d ever want to use a generic method since a non-generic method can access the generic members of its containing class and be passed generic arguments anyway.
So, using a canned example that likely misses the point (yet highlights why I’m asking this question), why would I do this:
public class SomeGeneric<T>
{
public T Swap<T>(ref T a, ref T b)
{
T tmp = a;
a = b;
b = tmp;
}
}
over
public class SomeGeneric<T>
{
public T Swap(ref T a, ref T b)
{
T tmp = a;
a = b;
b = tmp;
}
}
this?
Or, really, why would I want to use a generic method at all?
You’d typically use a generic method in a type that isn’t generic.
For example, look at the
Enumerableclass. It defines the generic extension methods for most of the LINQ fucntionaltiy, but itself isn’t generic.You also might want a generic method within a generic type, but only if the generic method used a different generic type specifier.
This lets you write something like the following:
(Granted, this is a bit contrived, but does compile and work correctly for
Foo<int>comparing to adouble, etc)