Is there a difference between a ternary operator and an if statement in C#? -
this question has answer here:
i'm working nullable datetime object , ran strange behavior. here's sample function:
public datetime? weird() { datetime check = datetime.now; datetime? dt; if (check == datetime.minvalue) dt = null; else dt = viewer.activethroughutc.tolocaltime(); //this line give compile error dt = (check == datetime.minvalue) ? (null) : (viewer.activethroughutc.tolocaltime()); return dt; }
as far know, line ternary operator should same preceding 4 lines, vs2010 giving me compile error, saying no conversion exists between <null>
, datetime (even though object in question 'datetime?'). there should know ternary operator or (gasp?) bug?
both elements in ?:
operator should of same type (but don't have - see details below). cast null
datetime?
:
dt = (check == datetime.minvalue) ? (datetime?)null : ...
from spec:
the second , third operands of ?: operator control type of conditional expression. let x , y types of second , third operands. then,
if x , y same type, type of conditional expression.
- otherwise, if implicit conversion (section 6.1) exists x y, not y x, y type of conditional expression.
- otherwise, if implicit conversion (section 6.1) exists y x, not x y, x type of conditional expression.
- otherwise, no expression type can determined, , compile-time error occurs.
(interestingly, it's not called "ternary" operator. it's one possible ternary (three-valued) operator, , i'm not aware of others in c#. it's called "?:" operator, little hard pronounce. called "conditional" operator.)
Comments
Post a Comment