Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic version vs interface version of a method

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);
}
like image 231
Hossein Narimani Rad Avatar asked Jan 21 '13 10:01

Hossein Narimani Rad


People also ask

How does a generic method differ from a generic type?

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.

What is a generic interface?

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.

Can a method be generic?

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.

What is a generic method and when should it be used?

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.


1 Answers

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.

like image 53
dtb Avatar answered Sep 21 '22 00:09

dtb