I stumbled with this issue, if I define a class
class MyClass<T,U> {
internal T myEement {get;set;}
public MyClass(T Element) {
myEement = Element;
}
}
And declare extensions.
static class MyClassExtension{
//What I want to do
public static void nonWorkingExtension<P,T,U>(this P p, U u) where P:MyClass<T,U>
{
T Element = p.myEement;
//Do something with u and p.Element
}
//What I have to do
public static void workingExtension<P, T, U>(this P p, T dummy, U u) where P : MyClass<T, U>
{
T Element = p.myEement;
//Do something with u and p.Element
}
}
When calling them:
MyClass<int, double> oClass = new MyClass<int, double>(3);
oClass.workingExtension(0,0.3); //I can call this one.
oClass.nonWorkingExtension(0.3); //I can't call this.
It exits with error.
Error 1 'MyClass' does not contain a definition for 'doSomething' and no extension method 'doSomething' accepting a first argument of type 'MyClass' could be found (are you missing a using directive or an assembly reference?)
After testing I found that the extension must use each generic parameter in a function attribute.
Why is this?
Are there any work arounds?
CONTEXT
Thanks to this answer I was able to implement constrains on generic classes (to make them behave like C++ template specialisation). The solution uses extensions constrains to produce compile time errors on non implemented specialisations.
(this P p, T dummy, U u) where P : MyClass, SomePolicy` inside `nonWorkingExtension(this MyClass p, U u)` where `MyClass` is a `SomePolicy`, but .net can't resolve P to SomePolicy.
– xvan Mar 16 '16 at 19:47