Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting CS0119 using a static method in a template?

Tags:

c#

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.

like image 429
Pete Avatar asked Jan 09 '14 14:01

Pete


2 Answers

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?

like image 88
JaredPar Avatar answered Oct 03 '22 23:10

JaredPar


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

like image 39
Leo Avatar answered Oct 03 '22 22:10

Leo