Let’s say I have a class Point:
class Point
{
public double? x, y;
}
In order to indicate that either x or y is an unknown, I’ve made their types nullable.
Now, when using these values in mathematical expressions, it’s inconvenient to have to cast their values to double each time. I.e. Math.Sin(p.x) will yield a compile time error; you must cast it instead: Math.Sin((double)p.x).
My approach for getting around the casting issue is to have wrapper read only properties which perform the casting:
class Point
{
public double? x, y;
public double X { get { if (x != null) return (double)x; else throw new Exception(); } }
public double Y { get { if (y != null) return (double)y; else throw new Exception(); } }
}
Is this a good approach?
You could use the
Valueproperty ofNullable:Or
This will throw an exception if the value has not been set, so is equivalent to your code.
Regarding the relative merits of the approaches:
IMO the property based approach shields consumers from the implementation detail that
xis internally stored as aNullableto represent unknown-ness. This would be my preference if consumers are only expected to deal with ‘known’ values. If however, consumers are expected to cater for a situation wherexremains ‘unknown’ then exposing aNullableproperty would be the way to go (and any consumers can check using theHasValueproperty ofNullable).