Is there a way to override the virtual generic method by replacing some or all of the type parameters?

Is there a way to override the virtual generic method by replacing some or all of the type parameters with actual type arguments?

class A1 { public virtual void Generic<T, U>(T t, U u) { } } class A2 : A1 { public override void Generic<T,int>(T t, int u) { } //error } 

thanks

+4
source share
3 answers

Try moving the general parameters to the class.

  class A1<T,U> { public virtual void Generic(T t, U u) { } } class A2<T> : A1<T , int> { public override void Generic(T t, int u) { } } 
+7
source

Your example is a bit ... general. I am sure that these classes make some sense, so the following architecture makes sense:

 class A1<U> { public virtual void Generic<T>(T t, U u) { } } class A2 : A1<int> { public override void Generic<T>(T t, int u) { } // no error } 
+5
source

As other answers showed, you can do this if the arguments of your function type match the parameters of the class type.

If they do not match, this is not possible because your example will violate type safety. Consider the following example:

 A1 a = new A2(); ... a.Generic<string, string>("", ""); 

This is a legal challenge since A1 provides Generic<T, U>(T t, U u) . But at runtime, we have a problem, since the dynamic type of a is A2 , and the version in A2 only supports int as the second parameter.

+1
source

All Articles