Jimmy
Jimmy

Reputation: 1082

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?

Upvotes: 0

Views: 60

Answers (3)

Sweeper
Sweeper

Reputation: 274975

Currently, this isn't possible, but as a workaround, you can use a using alias directive, provided that both interfaces are in the same file.

In the file that both interfaces are in, add a using alias directive like this:

using UserIdType = System.String;

Now, you can use UserIdType instead of String in both User and IUserService. When you want to change the type of the Id property, just change the using alias directive, and you don't have to change the types of either Id or the parameter userId.


However, wouldn't you still have to change the code that depends on the Id property? Changing one extra thing isn't that much of a trouble, compared to all the other code changes you'll have to make.

Upvotes: 0

nvoigt
nvoigt

Reputation: 77364

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.

Upvotes: 1

Samu
Samu

Reputation: 136

Maybe you could use a dynamic property?:

public dynamic Id { get; set; }

Upvotes: 0

Related Questions