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
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));
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With