2

I do have a lot of static classes that represent different states in different modules. However they share common algorithms that extract its information.

public static class Constants
{
    public static readonly int A = 0;
}

So for now I have for each class multiple static functions that does this. They only differ in the type of the static class that is processed (and its overall name).

public static SelectListItem getConstantsSelectListItem()
{ // pseudo example
     return new SelectListItem { Text = "A" , Value = Constants.A };
}

To remove current and avoid future codebloat, I'd like to use reflection on the static classes. Here's my approach, that would do the job (if it was possible):

public static ReturnType getProperties< T >()
{ // basically same logic as getConstantsSelectListItem
    var propertyList = typeof( T ) .GetFields( BindingFlags.Public | BindingFlags.Static ).ToList();

    foreach( var item in propertyList )
    {
        var curConstant = (int)( item.GetValue( null ) );

        // do some work here..
    }
}

var constantsProperties = getProperties<Constants>();

The error is:

static types cannot be used as argument types

I have read, that for generics only instances (and therefore no static classes) can be used.

What would be a good way to make something similar work?

nonsensation
  • 3,627
  • 6
  • 28
  • 41
  • Possible duplicate of [C# - static types cannot be used as type arguments](http://stackoverflow.com/questions/5858591/c-sharp-static-types-cannot-be-used-as-type-arguments) – IamK Oct 12 '15 at 09:59

2 Answers2

2

The question C# - static types cannot be used as type arguments explains very well that this behavior is intended.

It doesn't tell what you should do. In my opinion you could use a singleton pattern to keep one instance of that class. One benefit of this is that you can use inheritance too, so you don't need reflection to do the trick you do now, you can just rely on the base class' method signature.

Community
  • 1
  • 1
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
2

You can just pass a Type object as an argument instead of using generics. Since you have to do typeof(T) .GetFields( anyway, it's not like you have any static type safety that you're losing.

The other suggestion I would strongly make is to use dictionaries mapping strings to integers to represent your collections of constants. Using reflection like this is just giving you pain for no good reason, enforces weird, almost ritualistic rules on developers ("this static class is magic, don't add any strings"), and has worse performance.

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139