📎 Webclip
A dynamic definite assignment puzzle, part 2
Eric Lippert argues that the C# compiler is correct to flag the earlier program as a definite assignment problem. The key point is that dynamic forces the compiler to consider any runtime behavior that a legal but unusual type might produce, including odd operator overloads.
He builds the case with two contrived types. One makes && behave in a way that can skip evaluating the right-hand side, and another overloads equality so that obj != null can produce a non-bool result that still leads to a true if condition. That combination shows how GetString(out str) might never run even though the program later uses str. The practical fix is to cast dynamic to object before comparing with null, so the compiler can emit a normal null check.
Reading notes#
- The C# compiler is correct to report a definite assignment error for the original program.
dynamicmakes the compiler account for any valid runtime control flow, including very strange operator overloads.- The example uses a
Crazytype whoseoperator true,operator false, andoperator &behave in unnatural ways. - A second
Weirdtype overloads equality so thatobj != nullcan returnCrazyinstead ofbool. - With these overloads,
GetString(out str)can be skipped while theifcondition still evaluates as true. - The safe pattern is
(object)obj != null && GetString(out str). - The post also treats this as a lesson for language designers and compiler writers about operator overloading and adversarial test cases.
