Developing generic - wasting time?..

B

Bliss

I have some problems with my generic.

Part of code:
using System;
using System.Collections.Generic;
using System.Text;

namespace Gnrc
{
public class Gnrc<T>
{

//[some statements]

protected void SomeMethod()
{
T A, B, C;

//[some statements]

C = A + B; // CS0019: Operator '+' cannot be applied to operands of type 'T' and 'T'

//[some statements]
}
}
}

Is there available some "tricks" to bypass this error and compile ???
Of course, operator '+' is defined on 'T' type.

Best regards, Bliss.
 
N

Nicholas Paldino [.NET/C# MVP]

Bliss,

It might be defined on the type, but the compiler doesn't know it, and
can't apply it because the constraint system doesn't allow it.

Rather, you have to define your operations in an interface, and then
mark that as part of the constraint. Then, you can cast to your interface,
and perform operations on that.
 
P

Peter Duniho

[...]
Is there available some "tricks" to bypass this error and compile ???
Of course, operator '+' is defined on 'T' type.

Of course. :) But that doesn't mean that the generic class has any
way to represent that.

How much control do you have over the type used as T? If you can
modify the type, then one approach would be to define an interface that
requires the operator+ to be implemented, and then constrain T in the
generic to types that implement that interface.

If you can't create a type that allows for a suitable constraint in the
generic, then I don't believe you'll be able to do what you want.

Caveat: I haven't actually tried doing this. For all I know, operators
are a special case and can't be declared in an interface. If that's
true, then you may have to use a constraint that requires inheritance
of a specific class that implements the operator+ and of course make
sure your T type used inherits that class.

Pete
 

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