DEV Community 👩‍💻👨‍💻

Bernhard Speiser
Bernhard Speiser

Posted on

Outsmarting the C# Compiler - Using Static Types as Type Arguments

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
Enter fullscreen mode Exit fullscreen mode

This can be demonstrated by the following example:

static class StaticClass { }
static void Do<T>() => Console.WriteLine(typeof(T).FullName);

Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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.

Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)

Find what you were looking for? Join hundreds of thousands of developers on DEV so you can:

🌚 Enable dark mode
🔠 Change your default font
📚 Adjust your experience level to see more relevant content