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?
A static class can be used as a convenient container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields. For example, in the . NET Class Library, the static System.
C# Static types cannot be used as parameters.
A static class is similar to a class that is both abstract and sealed. The difference between a static class and a non-static class is that a static class cannot be instantiated or inherited and that all of the members of the class are static in nature.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With