I’ve often noted that “dynamic” in C# is just “object” with a funny hat on, but there are some subtleties to that. Here’s a little puzzle; see if you can figure it out. I’ll post the answer next time. Suppose we have this trivial little program:
static void Main()
object obj = GetObject();
if (obj != null && GetString(out str))
System.Console.WriteLine(obj + str);
static object GetObject() => “hello”
static bool GetString(out string str)
str = “goodbye”;
There’s no problem here. C# knows that
str is definitely assigned on every code path that reads it, because we do not enter the consequence of the
if statement unless
GetString returned normally, and methods that take
out parameters are required to write to the parameter before they return normally.
Now make a small change:
dynamic obj = GetObject();
C# now gives error CS0165: Use of unassigned local variable ‘str’
Is the C# compiler wrong to give this error? Why or why not?
Next time on FAIC: the solution to the puzzle.