MyAU85
MyAU85

Reputation: 15

How to restrict parameter types in generic methods

Say I have 3 classes: A,B and C. Each of these class have a GetValue() method, which returns an int. I want to create this method:

int GetTotalValue<T,R>(T c1, R c2)
{
  return c1.GetValue() + c2.GetValue()
}

Obviously, this won't work. As not all parameter types have a GetValue() method. So how do I restrict the parameter types T and R, so they have to have a GetValue() method (that returns an int)

Upvotes: 1

Views: 57

Answers (1)

David Arno
David Arno

Reputation: 43264

Have all three implement an interface that contains the GetValue method and constrain the method to using just those types.

public interface IGetValue
{
    int GetValue();
}

public class A : IGetValue  // Same for B and C
{
    ...
}

Then finally:

int GetTotalValue<T,R>(T c1, R c2) where T : IGetValue, R : IGetValue
{
    return c1.GetValue() + c2.GetValue();
}

UPDATE

As Alex points out in him comment, this method doesn't need to be generic though, it can be rewritten:

int GetTotalValue(IGetValue c1, IGetValue c2)
{
    return c1.GetValue() + c2.GetValue();
}

Upvotes: 2

Related Questions