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);

Do<StaticClass>();
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.

((dynamic)instance).Do<StaticClass>();
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 (1)

Collapse
 
mikejet profile image
Mike McWhinney

How would I apply this concept if a class was static.

I need to to set up a unit test and have this

private Mock mockLog;

clsLog is a static class:

public static class clsLog
{...
}

Do I change the class to be this?

public static class clsLog