I have a function which gives back a nullable struct.
I noticed two similar cases
First: works well:
public static GeometricCircle? CircleBySize(GeometricPoint point, double size)
{
if (size >= epsilon)
return null;
return new GeometricCircle(point.Position, new Vector(1, 0, 0), size, true);
}
Second: needs to convert the null value to GeometricCircle?
public static GeometricCircle? CircleBySize(GeometricPoint point, double size)
{
return size > epsilon ? new GeometricCircle(point.Position, new Vector(1, 0, 0), size, true) : (GeometricCircle?)null;
}
Does anybody know what is the difference?
In your first example, you are returning
nullwhensize >= epsilon. The compiler knows thatnullis a valid value for a nullable type.In your second example, you are using the
?:ternary operator, which comes with its own set of rules.MSDN tells us (my emphasis)…
The key difference here is that
nullcannot be implicitly converted into aGeometricCircle, (the type of yourfirst_expression).So you have to do it explicity, using a cast to
GeometricCircle?, which is then implicitly convertible toGeometricCircle.