A
OOP

Vector from float with operator inheritance in C#?

I need a data type with three float fields and at the same time without rewriting operators, that is

class Vector{ float X,Y,Z; }

operator+(vector A, vector B){ A.X += B.X; A.Y += B.Y;... }

so that you can write calmly
Vector a,b,c;
c = a + b;

but not
Vector a,b,c;
c.x = a.x + b.x;
c.y = a.y + b.y;
c.z = a.z + b.z;

how to avoid this I still need subtraction, multiplication. Is it possible to inherit the float class or operators? And if not, am I doing the right thing? are there any other options? and how to do it right?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sasha Pleshakov, 2016-08-19
@mnepoh

It seems impossible to do without redefining operators. How to override can be seen here

T
Tsiren Naimanov, 2016-08-19
@ImmortalCAT

The Vector3D you need is already created

D
Daniil Basmanov, 2016-08-19
@BasmanovDaniil

C# doesn't work like that, how can the compiler know what your class is and what should happen when adding? All operators need to be implemented by yourself. Writing three methods is a matter of a couple of minutes, you went to the toaster for longer. If the version of dotnet does not allow the use of built-in classes, you can peep the implementation in the Reference Source:
referencesource.microsoft.com/#System.Numerics/Sys...
referencesource.microsoft.com/#System.Numerics/Sys...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question