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 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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.