Search code examples
c#vectoralgebra

Custom compile-time checks


I don´t think that this question has (or can) been answered, or at least I didn´t find the answer: is it possible to create custom compile-time checks?

The specific situation is that I am programming a quantum spaces calculator, and while you could have vectors (1,0,0) and (1,0), I should modify certain operations between them as they belong to certain spaces. Even more, you could have (1,0) and (1,0) but neither of them belonging to the same spaces, so the operations between them would be different. But I don´t find a clever (not run-time) way to do this because they all belong to the same class so they have the same operators!

Also, the size of the vectors is arbitrary (from 0 to infinite) so I can´t make a class for all of them as a "Tuple".


Solution

  • You can try to use generics to prevent operations between different "vector" classes something like following concept code:

    class Vector<Traits> : IEnumerable<double> 
    {
        public static Vector<Traits> 
            operator + (Vector<Traits> left, Vector<Traits> right) { ... } 
    }
    
    var v1 = new Vector<MyTraitsOne>(2);    
    var v2 = new Vector<MyTraitsOther>(2);
    
    var r = v1 + v2; // should fail.
    

    (Traits class as generic's parameter in sample is solely to distinguish different vectors of double, but in real case there may even be good usage of such class)