Why does this (contrived) example give "error CS0119: 'T' is a 'type parameter', which is not valid in this context". Surely I have told it that the type will have a suitable method?
abstract class Foo
{
static public bool IsIt() {return true;}
}
class Bar
{
public bool CanIt<T>() where T : Foo
{
return T.IsIt();
}
}
The actual motivating example is something more complicated involving CRTP in the template parameter, but this shows the problem.
The C# compiler does not support the invocation of static methods off of type parameters.
Note that there is no value in doing this here. The call to IsIt
must be emitted when CanIt
is compiled. There is no way of invoking a static method in a virtual dispatch manner A static method can only be invoked by referring to the type + method directly. Hence the only thing the compiler could do here would be to emit a call to Foo::IsIt
. So why not just call Foo::IsIt
directly?
This answer is no news, but I guess you have a design issue here. Even though, this doesn't answer your question...why not go the OOP way? Why use generics when obviously you dont need them here? Why not make this CanIt
method just a plain OOP method and pass the abstract class as a parameter. Does IsIt
have to be a static method? Of course, it depends on what you are trying to achieve but I would make it a virtual method so others can override it as well. Again, I sniff design issues
abstract class Foo
{
public virtual bool IsIt() {return true;}
}
class Bar
{
public bool CanIt(Foo foo)
{
return foo.IsIt();
}
}
I believe it makes it simpler and easier to understand. Or perhaps I'm old-fashion...I don't know
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With