Search code examples
c#genericsinterfacesolid-principles

Is there a way to constrain a generic parameter type to the type of a certain property?


Please consider the following code:

public class User 
{
  public String Id {get; set;}
}

public interface IUserService 
{
  bool IsAdmin(string userId);
}

I would like to not specify the type of the userId parameter in the interface but rather use a generic type that is constrained to be of the same type as the property Id in the class User so that I don't have to change the code if I eventually decide to change the type of the property. So what I have in mind is something like:

public interface IUserService 
{
  bool IsAdmin<T>(T userId) where T : typeof(User.String)
}

Is that possible?


Solution

  • No, that's not possible. It's also not very useful to have a generic constrained to one specific type, that defeats the purpose of having a generic.

    What you could do is make your own type UserId (class or maybe struct) and use that in both places. So if your structure of what a user identifier is in your program changes, you can change it in one place and it works all over your program.