Generic parameters and the + operator

  • Thread starter Thread starter cpnet
  • Start date Start date
C

cpnet

There is probably an easy answer to this, but I haven't been able to find
it. I'm defining a method with 2 generic parameters like

void MyMethod<T>(T i1, T i2)

I want to be able to use the + operator in the body of my method:

T i3 = i1 + i2;

I can't figure out how to do this. I assume I need to add a constraint to
my method definition, but I can't figure out what contstraint I need to add.
 
cpnet said:
There is probably an easy answer to this, but I haven't been able to
find it. I'm defining a method with 2 generic parameters like

void MyMethod<T>(T i1, T i2)

I want to be able to use the + operator in the body of my method:

T i3 = i1 + i2;

I can't figure out how to do this.

You can't do this, at least not that easily.
I assume I need to add a
constraint to my method definition, but I can't figure out what
contstraint I need to add.

<http://www.codeproject.com/csharp/genericnumerics.asp?df=100&forumid=117139&exp=0&select=985597>

should pretty much cover it.

Regards,
 
cpnet,

Actually, you can't. The reason being is that there are a limited set
of constraints that are able to be used with generics now. Operators are
one of those things that are not able to be constrained upon. Because of
that, you can't do this.

Rather, you would have to define an interface, something like
IAddable<T> which defines a method:

T Add(T value)

And then call that on one or the other instance.

In reality, you should have an interface IAddition<T> which has one
method:

T Add(T value1, T value2)

The reason for this is that if both values are null, you can't call an
Add method on an instance of one of them. This way, if you have reference
types, you can still perform an operation.

Then, you should have a class factory that returns implementations of
IAddition (or IAdder, if that makes more sense) which is keyed on the type,
T. Then, you would call that.

Hope this helps.
 
The problem, as I am sure that you already know is that the object
passed in may or may not have a + operator defined. The generic
structure allows you to constraint the types that can be used by the
generic. where T : <base class name> could allow you to define your
generic in terms that require your type to derive from something that
always implements the + operator.
 
Thanks for all the answers. It's too bad that there isn't an easier way to
handle this - it seems like something pretty basic.
 
There's nothing basic about Generics.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
A watched clock never boils.
 
They are definitely more comlex than they seem at first. But I wasn't
meaning basic in terms of easy, but rather that regardless of the difficulty
support for pretty standard operations like +, - etc. would be handled.
 
Back
Top