KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I would expect the next three lines of code to be the same: public static void TestVarCoalescing(DateTime? nullableDateTime) { var dateTimeNullable1 = nullableDateTime.HasValue ? nullableDateTime : DateTime.Now; var dateTimeNullable2 = nullableDateTime != null ? nullableDateTime : DateTime.Now; var dateTimeWhatType = nullableDateTime ?? DateTime.Now; } In all cases, I assign nullableDateTime to the new variable. I would expect the type of all variables to become DateTime? since that is the type of nullableDateTime . But to my surprise, the type of dateTimeWhatType just becomes DateTime , so not nullable. To make things worse, ReSharper suggests to replace the second statement with a null coalescing expression, turning it into expression 3. So if I let ReSharper do its thing, the type of the variable will change from DateTime? to DateTime . In fact, let's say that in the remainder of the method, I would use if (someCondition) dateTimeNullable2 = null; That would compile just fine, until I let ReSharper replace the second expression with the null coalescing version. AFAIK, replacing somevar != null ? somevar : somedefault; with somevar ?? somedefault; should indeed produce the same result. But for implicit typing on a nullable type, the compiler seems to threat ?? as if it means. somevar != null ? somevar.Value : somedefault; So I guess my question is why the implicit type is changed when I use ?? , and also where in the documentation I could find info on this. BTW, this isn't a real world scenario, but I would like to know why using ?? changes the (implicit) type.
Tags (comma-separated)
Save Edits
Cancel