What is the difference between these two methods?
first:
public static int Foo<T>(T first, T second) where T:IComparable
{
return first.CompareTo(second)
}
second:
public static int Foo(IComparable first, IComparable second)
{
return first.CompareTo(second);
}
From the point of view of reflection, the difference between a generic type and an ordinary type is that a generic type has associated with it a set of type parameters (if it is a generic type definition) or type arguments (if it is a constructed type). A generic method differs from an ordinary method in the same way.
A generic interface is primarily a normal interface like any other. It can be used to declare a variable but assigned the appropriate class. It can be returned from a method. It can be passed as argument. You pass a generic interface primarily the same way you would an interface.
Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.
Generic methods allow type parameters to be used to express dependencies among the types of one or more arguments to a method and/or its return type. If there isn't such a dependency, a generic method should not be used. It is possible to use both generic methods and wildcards in tandem.
For the first method, the types of the two parameters have to be same, e.g., int
and int
. The type has to implement the IComparable
interface.
For the second method, the two parameters can have different types. Both types must implement the IComparable
interface, but do not have to be the same, e.g., int
and string
.
Note that the IComparable.CompareTo method will likely throw an exception if the types are not the same. So it's better to make sure that the types are actually the same. You can do this by using your first method, or even better by using the generic IComparable<T> interface.
The follow-up question is, of course: What is the difference between these two methods?
first:
public static int Foo<T1, T2>(T1 first, T2 second) where T1 : IComparable<T2>
{
return first.CompareTo(second);
}
second:
public static int Foo<T>(IComparable<T> first, T second)
{
return first.CompareTo(second)
}
Answer: The first method doesn't box the first argument, while the second method does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With