c# - Nullable <= vs == comparison result -
this behaviour sounds wrong me.
datetime? birth = null; datetime? death = null; console.writeline(birth == death); // true console.writeline(birth <= death); // false
why so? incredibly strange. of course mean why second expression not evaluate true
well.
edit:
i understand following comparisons return false
, because cannot said how relate each other:
console.writeline(birth < death); // false console.writeline(birth > death); // false
this understandable behaviour. but... @ logic:
<=
means<
or==
- we don't know how read
<
-true
orfalse
- we know
==
true
- since 1 of conditions
true
, other condition cannot untrue result. logic or, not and.
my point true or else
should true.
i know c# team designed way, intuition different. since smart people have written c# such rules, want learn why intuition wrong here :)
i understand not looking specs explanation of why nullables designed way.
to remove ambiguity, designers have let these operators return bool?
value instead of bool
value null in case 1 of operands null.
but if had made choice, code like:
bool? comparison = birth <= death; if (comparison.hasvalue && comparison.value) { }
which bit cumbersome.
as side note, seems like, looking @ il, c# compiler generates comparison default values first , checks if 1 of operands null seems bit odd...
.method private hidebysig static void main(string[] args) cil managed { .locals init ([0] valuetype [mscorlib]system.nullable`1<int32> x, [1] valuetype [mscorlib]system.nullable`1<int32> v_1, [2] valuetype [mscorlib]system.nullable`1<int32> v_2) il_0000: ldloca.s x il_0002: ldc.i4.1 il_0003: call instance void valuetype [mscorlib]system.nullable`1<int32>::.ctor(!0) il_0008: ldc.i4.2 il_0009: newobj instance void valuetype [mscorlib]system.nullable`1<int32>::.ctor(!0) il_000e: ldloc.0 il_000f: stloc.1 il_0010: stloc.2 il_0011: ldloca.s v_1 il_0013: call instance !0 valuetype [mscorlib]system.nullable`1<int32>::getvalueordefault() il_0018: ldloca.s v_2 il_001a: call instance !0 valuetype [mscorlib]system.nullable`1<int32>::getvalueordefault() il_001f: ble.s il_0024 il_0021: ldc.i4.0 il_0022: br.s il_0033 il_0024: ldloca.s v_1 il_0026: call instance bool valuetype [mscorlib]system.nullable`1<int32>::get_hasvalue() il_002b: ldloca.s v_2 il_002d: call instance bool valuetype [mscorlib]system.nullable`1<int32>::get_hasvalue() il_0032: , il_0033: brfalse.s il_003a il_0035: call void [mscorlib]system.console::writeline() il_003a: ret } // end of method program::main
it replicating logic present in static nullable class.
Comments
Post a Comment