> How can I use * operator in C# generics? e.g.
>
> class foo<T_>
> {
> T_ v1, v2:
>
> public T_ squar()
> {
> return v1 * v2; /// wrong!
> }
> }
I don't think you can. To use the * operator (or any operator, for that
matter), the compiler has to know that you're dealing with types that have
a defined overload for the operator.
If you have a situation where you can constrain your generic type
parameter to one that does have a valid operator* overload, then that
would work. But without any other information from you, it seems likely
that you're looking to get this behavior with value types and of course
they don't have any inheritance relationship that would allow you to
define a useful constraint like that.
I suppose you could define overloads within your class, covering all the
types you want to handle. I haven't tried it myself, but hopefully the
compiler would be able to pick the right overload at compile time. For
example:
class foo<T_>
{
T_ v1, v2;
public static T_ squar(int t1, int t2)
{
return (T_)(t1 * t2);
}
public static T_ squar(float t1, float t2)
{
return (T_)(t1 * t2);
}
// etc.
public T_ squar()
{
return squar(v1, v2);
}
}
Actually, seeing that in code, I'm not so sure. The compiler might sitll
find something to complain about. But it's worth a try anyway.
Pete
It's a well known problem -- you can't.
Search codeproject for "C# generic arithmetic" for workarounds.
> [...]
> No, overload resolution in generics is done based on the constraints
> only, not the final type. This is what lets generics be exported in
> MSIL form, as opposed to C++ templates which do overload resolution for
> each actual combination of type parameters but can only be shared in
> source form.
Oh well, it was worth a try. :) I'm a bit confused though: I thought
that for value types, a new instance of the class was generated for each
variation of the generic class.
In other words, while I do expect the problem you're describing with
reference types, I thought there was a chance that the compiler would
resolve things early enough for value types that the overloading and
casting would be okay.
Of course, if I'd tried to compile it I'd know for sure. I'm not
questioning what you're saying, just trying to figure out why, if value
types are handled differently anyway, they aren't a work-around for this
problem.
Pete
The JIT will spit out new native code for each value type, but the
compiler keeps it in a single generic type.
--
Jon Skeet - <sk...@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
For info, for people using . NET 3.5 I have a usable solution for
this. It doesn't (unfortunately) offer compile-time checking, but it
provides very efficient access to all the common operators. Quick
enough to be directly comparable to regular compiled code.
Let me know if people are interested...
Marc
At least then we could use a generic constraint (amongst other things)
for issues like this.
Chris.
In explaining it to a friend, I think the easiest way of thinking about
them is as "duck-typed operators" :)
(I hasten to add that while I understand the principle of the thing, I
don't understand Marc's code... :)
For the group's benefit - that doesn't mean that it is hard to use -
consider the following, for example, that works for *any* type that
declares a suitable add operator (even your own bespoke
"ComplexInt32"). If it can't find the operator it will throw an
InvalidOperationException at runtime - but it will run almost as
quickly as a specific overload implementation:
public static T Sum<T>(this IEnumerable<T> source)
{
if (source == null) throw new ArgumentNullException();
T sum = Operator<T>.Zero; // not the same as default(T);
think "int?"
foreach (T value in source)
{
if (value != null)
{ // ignore nulls (think "int?"; recall 0 + null =
null)
sum = Operator.Add(sum, value);
}
}
return sum;
}
>> Oh well, it was worth a try. :) I'm a bit confused though: I thought
>> that for value types, a new instance of the class was generated for each
>> variation of the generic class.
>
> The JIT will spit out new native code for each value type, but the
> compiler keeps it in a single generic type.
Ahh...I thought it was the C# compiler doing that work. Okay then...I can
see how if the C# compiler always keeps a single generic type, why it then
has the limitations Ben describes. Thanks!
Pete
Aside from anything else, operators are static, so can't be part of an
interface implementation.
I think with a big change to a lot of stuff it would be possible, but
MS hasn't got round to it yet...
Sorry, yes, I should have made that clear. It's incredibly easy to use
- the implementation is just slightly confusing, due to being in
expression trees, which are fundamentally hard to get your head round
(well, so I find).
A number of such have been proposed (as discussion points on forums
like this), but they all suffer from the fact that our current
understanding of operators is much more flexible than a standard
interface would permit. Often there are operators against a range of
different types with different outputs, so the signatures of the
methods would be tricky - it isn't always T with "T Operator(T arg)".
The nature of maths is an issue too - the operations supported by
different number systems are not consistent; "uint", for instance,
doesn't define "negate" (additive inverse). Likewise the int-based
numbers don't define "reciprocol" (multiplicative inverse), nor do non-
square matrices. Division is better supported, but still has issues.
This means that either you'd have a ridiculous number of (probably
generic) interfaces (with 1, maybe 2 methods each), or you'd have a
few interfaces (with lots of simple T=>T methods) where you already
know that some methods are reasonably likely to throw "NotSupported"
or "InvalidOperation" (because they simply don't make sense for that
number system).
The first option (lots of interfaces) becomes very restrictive and
almost impossible to use; the second (untrustworthy interfaces)
doesn't buy an awful lot of *true* safety anyway.
Thus I propose that the duck-typing (to borrow Jon's usage) is
certainly no worse than anything else we can currently propose; but it
works, exists today, and is as quick as you'd like.
For completeness, I have also seen a previous reply on this subject
that the number of interfaces, members, virtcalls, etc (against the
primatives) would have a significant impact on things like CF. I don't
know about the truth of this claim, however.
Marc
This complexity is part of what my code attempts to avoid (albeit with
its own complexities ;-p).
Lutz Roeder's .NET Reflector will easily show you which operators
exist for which primatives.
Marc
It can certainly be done - it just isn't as simple as it might appear
at first inspection. I'm lazy, so I didn't do it this way...
Marc