I have the following property in my code
public float X {
get {
if (parent != null)
return parent.X + position.X;
return position.X;
}
set { position.X = value; }
}
I was hoping to convert the getter into the form of
get {
return parent?.X + position.X;
}
But I get the following error: Cannot implicitly convert type 'float?' to 'float'. An explicit conversion exists (are you missing a cast?)
Am I doing something wrong or is it not available right now?
The type of parent?.X
is float?
, which you're adding to a float
- resulting in another float?
. That can't be implicitly converted to float
.
While Yuval's answer should work, I would personally use something like:
get
{
return (parent?.X ?? 0f) + position.X;
}
or
get
{
return (parent?.X).GetValueOrDefault() + position.X;
}
I'm not sure of your design, mind you - the fact that you add something in the getter but not in the setter is odd. It means that:
foo.X = foo.X;
... will not be a no-op if parent
is non-null with a non-zero X
value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With