Home > Enterprise >  Can I use static field of T in a generic class
Can I use static field of T in a generic class

Time:06-09

I want to get the static property (or field, which I don't care) inside a generic class, my code looks like this:

public interface IModel{
    static string Name {get;}
}

public class MyModel : IModel{
    static string Name {get;}
}

public class ViewModel<TModel> where TModel : IModel{
    public string GetName(){
        return TModel.Name;
    }
}

But I got this error:

CS0119: TModel is a type parameter, which is not valid in given context

As I guess, TModel is a type, not the actual class. So what should I do, or is it just not possible?

CodePudding user response:

There is an experimental C# feature which will do what you want.

But until then, you can work around it using a separate static generic class

public interface IModel{
}

public static class IModelStatics<TModel> where TModel : IModel{
    public static string Name {get;}
}

public class MyModel : IModel{
}

public class ViewModel<TModel> where TModel : IModel{
    public string GetName(){
        return IModelStatics<TModel>.Name;
    }
}

CodePudding user response:

Currently, C# does not allow you to access static member of a generic type, so you have to use reflection

public class ViewModel<TModel> where TModel : IModel{
    public string GetName(){
        return (string)typeof(TModel).GetProperty("Name", BindingFlags.Public | BindingFlags.Static).GetValue(null, null);
    }
}

CodePudding user response:

There is no such a feature as static fields in Interface for no reason. That is not how interfaces supposed to work. Do you really need to make it Static? Maybe it would be better if you create a new instance of an object like that:

public interface IModel
{
    public string Name { get; }
}

public class MyModel : IModel
{
    public string Name { get; } = "MyName";
}

public class ViewModel<TModel> where TModel : IModel, new()
{
    public string GetName()
    {
        return (new TModel()).Name;
    }
}
  • Related