create a vector class in csharp

To create a vector class in C#, you can define a new class with fields representing the vector's x, y, and z components. You can also define methods for performing common operations on vectors, such as adding, subtracting, and scaling.

main.cs
public class Vector
{
    public double X { get; set; }
    public double Y { get; set; }
    public double Z { get; set; }

    public Vector(double x, double y, double z)
    {
        X = x;
        Y = y;
        Z = z;
    }

    public double Magnitude()
    {
        return Math.Sqrt(X * X + Y * Y + Z * Z);
    }

    public static Vector operator +(Vector v1, Vector v2)
    {
        return new Vector(v1.X + v2.X, v1.Y + v2.Y, v1.Z + v2.Z);
    }

    public static Vector operator -(Vector v1, Vector v2)
    {
        return new Vector(v1.X - v2.X, v1.Y - v2.Y, v1.Z - v2.Z);
    }

    public static Vector operator *(Vector v, double scalar)
    {
        return new Vector(v.X * scalar, v.Y * scalar, v.Z * scalar);
    }

    public static Vector operator /(Vector v, double scalar)
    {
        return new Vector(v.X / scalar, v.Y / scalar, v.Z / scalar);
    }
}
884 chars
39 lines

With this class defined, you can create new Vector objects, perform operations on them, and calculate their magnitude:

main.cs
Vector v1 = new Vector(1, 2, 3);
Vector v2 = new Vector(4, 5, 6);

Vector v3 = v1 + v2;
Vector v4 = v1 - v2;
Vector v5 = v1 * 2;
Vector v6 = v2 / 2;

double magnitude = v1.Magnitude();
185 chars
10 lines

gistlibby LogSnag