Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • C# - static types cannot be used as type arguments
  • C# Static types cannot be used as parameters

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?

like image 843
Lazlo Avatar asked Apr 28 '17 19:04

Lazlo


People also ask

What are static classes used for?

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.

Can we pass static class as parameter in C#?

C# Static types cannot be used as parameters.

What are static classes?

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.


1 Answers

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

like image 121
Chris Bartlett Avatar answered Sep 20 '22 16:09

Chris Bartlett