Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use where for operators at generics class c#? [duplicate]

Hi I would like to have a class:

class Matrix <T>
    where T : // I don't know what to write here
{
    T[][] elements;
}

I would like T to be addable and multiplyable by + and * operators

like image 522
Dániel Kovács Avatar asked Feb 07 '13 18:02

Dániel Kovács


2 Answers

I would highly recommend you take a look at the "MiscUtil" library from Messrs Skeet and Gravell:

http://www.yoda.arachsys.com/csharp/miscutil/

Contained within is an incredible "generic math operators" implementation, which should line up nicely with your attempts to create a generic matrix math class. It actually reminds me (a bit) of python and how it handles referencing the operator functions directly.

(aside to @jon-skeet : any chance of this making its way to Nuget?)

Some example usages from their tests:

double sumOperator = 0;
for (int i = 0; i < COUNT; i++)
{
    sumOperator = Operator.Add(sumOperator, rand.NextDouble());
}

int sumOperator = 0;
for (int i = 0; i < COUNT; i++)
{
    sumOperator = Operator.Add(sumOperator, rand.Next(MAXVALUE));
}
like image 56
JerKimball Avatar answered Oct 16 '22 00:10

JerKimball


This is not possible because the unconstrained generic type is assumed to be of type Object, which doesn't define the arithmetic operators. Hence, it seems you need to specify an interface.

But, the primitive types (Int32, Double, etc) define the arithmetic operations effectively as static methods (actually the compiler treats them specially and generates the code inline) and an interface in C# cannot define static methods (although the design of the CLR actually allows it). Hence, no interface be written in C# which satisfies the requirements of supporting the arithmetic operations; even if it could be written, the primitive types don't inherit it, so it still wouldn't work.

The end result is that there's no way to do what you want in C#.

If you do try it, you get an error similar to

Operator '+' cannot be applied to operands of type 'T' and 'T'

If you do a web search for this message, you'll find various discussions about possible workarounds.

like image 42
StarNamer Avatar answered Oct 15 '22 23:10

StarNamer