tags:

views:

229

answers:

2

Is there any good way to create a generic Vector4 class in C#? I have a couple of units(force, distance, moment, rotation, acceleration, velocity etc) that all need a 3d-representation and they all behave very similar and should therefore support the basic functions for adding, multiplying etc.

Each class also contain some special cases, for example force⨯distance=moment. Therefore i want to be able to create a Force3d inheriting from Vector4<Force> so i don't have to write all those arrows all the time and to be able to add these force-specific functions to the struct.

I've been using this inherit-based approach, where every unit inherits from Vector4, until now but this causes some problems because when i for example call Add(force1, force2) i get the baseclass, Vector4, back instead of a Force3d. So i end up either casting or creating a copy of the Add-function for every unit.

I want to be able to create both a Vector4<double> and a Vector4<Force> without having to redefine all basic functions for adding, multiplying etc(preferably with the real operators, which seems impossible). This also adds some new problems because the best solution would be to make Force inherit from double but since all base types are sealed i have to create a containerclass and i end up redefining the basic operators for numbers here instead.

I've been trying every approach possible but i always end up redefining way too much stuff.

A: 

You should only need to create generic operator overloads for the base Vector4<T> class. As long as your Force class overloads its own operators correctly, then this shouldn't be a problem, since using operators on objects of generic types should correctly resolve to the appropiate overloads.

Noldorin
Reason for down vote please?
Noldorin
+1  A: 

Regarding overloading operators, there is a solution here which explains how to do it using .Net 3.5 (using Jon Skeet's MiscUtil library).

To get the correct type in methods' results, you can use something like:

public class Vector<T>
{
    public T x { get; }
    public T y { get; }
}

public class VectorWithOperators<TVector, T> : Vector<T> 
   where TVector : Vector<T>, new()
{
    public TVector GetSomeResult()
    {
        return new TVector();
    }
}

public class Force3D : VectorWithOperators<Force3D, double>
{
}
Groo