Limitless Limitless - 7 months ago 30
C# Question

C# Adding classes with one another

So I was playing around with "Vectors" in C# I created my own Vector class.
What I tried to do was to add two vectors with each other by a simple "+".
This is my vector class:

class createVector
//My x,y,z coordinates
public int x { get; set; }
public int y { get; set; }
public int z { get; set; }

public createVector(int X, int Y, int Z=0)
x = X;
y = Y;
z = Z;

// Convert to String
public override string ToString()
return string.Format("X:{0,-5}\nY:{1,-5}\nZ:{2,-5}", x, y, z);

And what I attempted to do was this:

createVector Vector1 = new createVector(1, 2);
createVector Vector2 = new createVector(3, 4, 5);

createVector Vector 3 = Vector1 + Vector2;

I don't want to use a function to add the Vectors together.

Is it possible for me to do something like this?


You need to overload the + operator inside the class:

public static Vector operator +(Vector v1, Vector v2) 
    // do logic here then return a vector
    return new Vector (); 

It is better to follow .NET naming conventions and have your class named Vector and not createVector. It should be a noun and using PascalCase .