How to construct C# generic classes while using external library types?

39 Views Asked by At

I've recently stumbled upon an issue: I've been using the System.Numerics library for the Vector3 object, which is only of float precision. I later found out in some cases I needed double precision for which I'm using the System.DoubleNumerics library, which is an equivalent to System.Numerics, but isn't SIMD-accelerated and uses double precision. In my code I use a class that has the Vector3 as a property:

using System.Numerics;

public class MyClass
    {
        // ...some code
        public Vector3 Coordinate { get; set; }
    }

I'd like to turn this class into a generic class supporting both double and float and use System.Numerics.Vector3 or System.DoubleNumerics.Vector3 depending on the situation. My problem is how to do this the best way possible.

One way to do this would be to have the type of the property as object and set it after reading the typeof(T) as one of the two Vector3 types. This would be at the cost that everywhere I call this property, I have to cast to the actual Vector3 type. That's probably not a fatal sacrifice, but I'd like to know if there would be any cleaner way to do this. Thank you for any recommendations.

1

There are 1 best solutions below

0
Lajos Arpad On

You could create an abstract class that declares the methods you are to use and subclasses that implement them. You could define an object factory method in the abstract class that infers the type via GetGenericTypeDefinition and instantiate the appropriate subclass based on type. And the subclass will handle the tasks from there on.

Of course, you could do method overloading, but if you have to use similar names of multiple namespaces, then this may be a less attractive option in this particular case.