Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two generic methods with the same name

Tags:

c#

generics

Is not possible (except use different name) to have several generic methods with the same name but implementing different interface ?

public IList<T> List<T>() where T : class, IMyInterface1
{

    return mylist
}

public IList<T> List<T>() where T : class, IMyInterface2
{

    return mylist
}

Thanks,

like image 315
Kris-I Avatar asked Jul 16 '12 08:07

Kris-I


People also ask

Can a generic class have multiple generic parameters?

A Generic class can have muliple type parameters.

Can we define more than one generic datatype in a class?

You can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.

Can generic methods be static?

Static and non-static generic methods are allowed, as well as generic class constructors. The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type.

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. Here is the method Collections.


1 Answers

No, you can't overload just by generic type constaints. You can overload by the number of type parameters, but not on their constraints.

If you're implementing an interface you can use explicit interface implementation - otherwise I'd suggest just using different names. I often find that using different names makes things clearer anyway, to be honest.

Bear in mind that the example you've given introduces natural ambiguity anyway - what would you expect to be called if the type argument implemented both interfaces?

like image 63
Jon Skeet Avatar answered Oct 13 '22 19:10

Jon Skeet