I have a type that represents a type of number. In this case, I’m working with megawatts, so I have created a type called Megawatt. I’d like to be able to work with these megawatts like I would an Int, Double, or any type of c# number type. Is this possible? If so, how do I do it?
Example:
public class Megawatt{
public double Value { get; set; }
}
I want to be able to do this:
var startOfDay = new Megawatts{value=100};
var endOfDay = new Megawatts{value=65};
Megawatt result = startOfDay - endOfDay;
This is possible with DateTime… you can subtract one DateTime from another and get a TimeSpan. I’m hoping to do something similar.
In addition to the good answers posted so far: you should make your type an immutable struct rather than a mutable value type. This is precisely the sort of job that immutable value types were designed for.
And so on. Note that you can add together two megawatts, but you cannot multiply two megawatts; you can only multiply megawatts by doubles.
You could also add more unit-laden types. For example, you could create a type MegawattHour and a type Hour and then say that Megawatt times Hour gives MegawattHour. You could also say that there is another type Joule, and there is an implicit conversion from MegawattHour to Joule.
There are a number of programming languages that support these sorts of operations with less verbosity than C#; if you do a lot of this sort of thing you might look into F#.