Search code examples
c#.netreflectionclr

Static classes can be used as type arguments via reflection


When trying to use a static class as a type parameter, the C# compiler will throw an error:

var test = new List<Math>();

error CS0718: `System.Math': static classes cannot be used as generic arguments

This has been covered in these questions:

However, I just realized I can create the type via reflection, and the runtime won't complain:

var test = Activator.CreateInstance(typeof(List<>).MakeGenericType(typeof(Math)));

Am I right in concluding this is supported at the CLR level, but not at the language level?

Or is this a gray area in specifications, meaning I should refrain from using these generic constructed types?


Solution

  • As stated in the comment from BJ Myers, the CLR has no knowledge of "static" classes. The compiler errors are there to prevent you from doing things that can cause serious issues. There are almost always ways around most errors like this (in this case using reflection), but the error when trying to pass the static class as a parameter is a good indication that you should not be doing what you are doing unless you know very well what the repercussions are.

    In this case, you should be asking yourself, why are you wanting to pass a static class? Since a static class can have no references to data or other objects, there is no point to pass this. If you need to call functions on a static class without having an explicit reference to it, you can use reflection to invoke its methods. Here is an answer explaining that:

    Invoking static methods with reflection