confusion about generics

W

Wiktor Zychla

I've read several documents about upcoming C# generics and I still cannot
understand one thing.

Would it be valid to write a code like this:

class SomeClass
{
public void AMethod<T>(T a, T b)
{
T c = a + b; // ?
...
}
}

since + is defined for some simple types and can be overloaded for reference
types, then what kind of constraint should be used to allow the + in above
context?

or would it be forbidden to use standard binary operators in generic code?
(in fact, it would require to have the interface, IAddable, make all numeric
types implement the interface and then add "where T : IAddable" to the above
code)

if it is forbidden to use + in above context, then how will I create a
generic class that acts like this one above? (suppose I need to call the
method AMethod with any class that supports + operation, including <int>
<double> and other numeric types).

I would really like to hear from an expert on this issue.
Thanks in advance.

Wiktor Zychla
 
N

Nicholas Paldino [.NET/C# MVP]

Wiktor,

The constraint mechanism doesn't define operators on the type as a
constraint. Because of this, you will have to get around it in some other
way. Like you specified, an interface which indicates that the operation
could be performed would be the best way to go.

Generally speaking, I think that using an operation for a constraint
would be a bad idea anyways, since not all .NET languages support operator
overloads (VB for example) and you would limit generics on those platforms.
However, interfaces are accessible in all languages (or at least, more
accessible than overloaded operators).

Because of this, you should have a constraint on an IAddable interface
and then use the Add method on that interface (I am guessing this would be
there).

But, this raises the problem of what do you do for already defined
classes which expose this functionality and can not be changed to implement
IAddable? In this case, you will have to check the type of T, and then find
the static method that corresponds to the operator overload (op_Addition).
If it exists, then you can call that through Reflection. I know it is
painful, but it is the only way with the way generics are currently
proposed.

Hope this helps.
 
W

Wiktor Zychla

But, this raises the problem of what do you do for already defined
classes which expose this functionality and can not be changed to implement
IAddable? In this case, you will have to check the type of T, and then
find

this is exactly what I wanted to hear. as usual, thanks Nicholas.
regards, Wiktor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top