I wonder if there is a way in C # to have a type based on a primitive type and duplicate it to use other primitives.
I know this is not very clear, I don’t know how to explain it (and English is not my native language, sorry for that ...), so I will try to explain it using pseudocode.
Quick example:
public struct Vector2d { public double X; public double Y;
The problem is that I would like to have a float and an int32 version of this type.
What I am actually doing (valid C # code):
//This type contains all useful methods public struct Vector2d { public float X; public float Y; public Vector2f AsFloat() { return new Vector2f((float)X, (float)Y); } public Vector2f AsInteger() { return new Vector2i((int)X, (int)Y); } //Arithmetic methods } //These types are only here to be casted from/to, all the arithmetics methods are on the double-based type public struct Vector2f { public float X; public float Y; public Vector2f AsDouble() { return new Vector2d(X, Y); } public Vector2f AsInteger() { return new Vector2i((int)X, (int)Y); } } public struct Vector2i { public int X; public int Y; public Vector2f AsFloat() { return new Vector2f(X, Y); } public Vector2f AsDouble() { return new Vector2d(X, Y); } }
This works, but it is not “sexy,” and in the case of extensive tricks using AsXXX methods, it will inevitably affect performance.
Ideally, I would have had arithmetic methods for all three types, but it would be painful to maintain ...
What would be the perfect solution (pseudo-code, invalid C #):
public struct Vector2<T> where T : numeric { public TX; public TY; public T Length { return (T)Math.Sqrt(X * X + Y * Y); }
I know this is not possible in C # at the moment, but here is the true question:
Do you have any ideas on how to handle this beautifully and effectively?
What I was thinking about (pseudo code, invalid C #):
//The TYPE defined constant should be used by Vector2Body instead of plain typed "double", "float", etc... public struct Vector2d {
This way I would not have duplicated code, it’s easier to maintain
Waiting for your ideas :)
PS: If the moderator has ideas on how best to format my question, feel free to edit it :)