Outsmarting the C# Compiler - Using Static Types as Type Arguments
Bernhard Speiser
Posted on September 16, 2021
In case you were not aware, the C# compiler prevents you from using static types as type arguments. Trying to use a static type will result in the compiler error CS0718.
error CS0718:
'StaticClass': static types cannot be used as type arguments
This can be demonstrated by the following example:
static class StaticClass { }
static void Do<T>() => Console.WriteLine(typeof(T).FullName);
Do<StaticClass>();
Outsmarting the Compiler
We need to move the Do<T>
method into a new class and instantiate an instance of that class.
class MyClass
{
public void Do<T>() => Console.WriteLine(typeof(T).FullName);
}
var instance = new MyClass();
This alone will not "fix" the issue, as calling instance.Do<StaticClass>()
still results in the same compiler error.
This is where dynamic
comes into play.
((dynamic)instance).Do<StaticClass>();
Since instance
is now of type dynamic
the compiler will not verify the Do
call at compile time, but at runtime. Now the code builds. Running it will print StaticClass
to the console, which indicates that only the compiler prevents a type argument from being static, although the runtime can handle static types as type arguments.
The need to outsmart the compiler, in most cases, indicates that there is something wrong with your design. Remember, just because you can, doesn't mean you should.
Posted on September 16, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.