Reputation: 2202
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?
Upvotes: 3
Views: 277
Reputation: 54117
In your first example, you are returning null
when size >= epsilon
. The compiler knows that null
is 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.
condition ? first_expression : second_expression;
MSDN tells us (my emphasis)...
Either the type of
first_expression
andsecond_expression
must be the same, or an implicit conversion must exist from one type to the other.
The key difference here is that null
cannot be implicitly converted into a GeometricCircle
, (the type of your first_expression
).
So you have to do it explicity, using a cast to GeometricCircle?
, which is then implicitly convertible to GeometricCircle
.
Upvotes: 5