Last Updated on January 30, 2021 by sandeeppote

Consider if you want to use if and only if condition (IIF) with a nullable type

DateTime? foo;
foo = true ? null : new DateTime(0);

This will throw a compiler error. To resolve this cast null to nullable type as below-

foo = true ? (DateTime?)null : new DateTime(0);