Overloading Methods That Use Type Parameters


Methods that use type parameters can be overloaded. However, the rules are a bit more stringent than they are for methods that don’t use type parameters. In general, methods that use type parameters can be overloaded as long as their signatures differ. This means that the type and/or number of their parameters must differ. However, the determination of type difference is not based on the generic type parameter, but on the type argument substituted for the type parameter when a constructed type is created. Therefore, it is possible to overload a method that uses type parameters in such a way that it “looks right,” but won’t work in all specific cases.

For example, consider this generic class:

 // Ambiguity can result when overloading // methods that use type parameters. // // This program will not compile. using System; // A generic class that contains a potentially // ambiguous overload of the set() method. class Gen<T, V> {   T ob1;   V ob2;   // ...   // In some cases, these two methods   // will not differ in their parameter types.   public void set(T o) {     ob1 = o;   }   public void set(V o) {     ob2 = o;   } } class AmbiguityDemo {   public static void Main() {     Gen<int, double> ok = new Gen<int, double>();     Gen<int, int> notOK = new Gen<int, int>();     ok.set(10); // is valid, types differ     notOK.set(10); // ambiguous, types are the same   } }

Let’s examine this program closely. First, notice that Gen declares two type parameters: T and V. Inside Gen, set( ) is overloaded based on parameters of type T and V, as shown here:

 public void set(T o) {   ob1 = o; } public void set(V o) {   ob2 = o; }

This looks reasonable because T and V appear to be different types. However, this overloading creates a potential ambiguity problem.

As Gen is written, there is no requirement that T and V actually be different types. For example, it is perfectly correct (in principle) to construct a Gen object as shown here:

 Gen<int, int> notOK = new Gen<int, int>();

In this case, both T and V will be replaced by int. This makes both versions of set( ) identical, which is, of course, an error. Thus, when the attempt to call set( ) on notOK occurs later in Main( ), a compile-time ambiguity error is reported.

In general, you can overload methods that use type parameters as long as there is no constructed type that results in a conflict. It is important to understand that type constraints do not participate in overload resolution. Thus, type constraints cannot be used to eliminate ambiguity. Like methods, constructors, operators, and indexers that use type parameters can also be overloaded, and the same rules apply.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net