WhiteBlackGoose / UnitsOfMeasure

Conceptual repo. Most advanced compile time safe units of measure for C# and F#
MIT License
57 stars 4 forks source link

Utilize Operator Overloads rather than extension Methods #6

Open dan-drews opened 2 years ago

dan-drews commented 2 years ago

First, I read your blog post about this and think this implementation of units is brilliant! As I was reading it though I was intrigued by the usage of .Add() rather than +, so I wanted to dig into the feasibility of operator overloads.

I just started digging into this and tried to take a stab at it myself. I failed to do so, but am willing to give it another shot in the future.

Rather than having the following

var distance = 5f.Meters();
var time = 4f.Seconds();
var speed = distance.Divide(time);

Is there a reasonable way within C# to do operator overloading on generic structs with interfaces?

var distance = 5f.Meters();
var time = 4f.Seconds();
var speed = distance / time;

Operator overloads declared at a class or struct level, and based on my limited research, there is no way to do thee via an extension method. Additionally, I'm unsure about the difficulties that come with different generic values in operator overloads.\

If this is impossible, I'm fine with closing it out, but if a workaround can be used I'd love to see this added.

WhiteBlackGoose commented 2 years ago

I agree that operators would be better. However, I want to allow to add values of different units, e. g. kilograms and grams, or km/s and mile/min, and so the operator itself should be generic. But operators aren't generic in C#... yet.