Article 42YCT A dynamic definite assignment puzzle

A dynamic definite assignment puzzle

by
ericlippert
from Fabulous adventures in coding on (#42YCT)
Story Image

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:

class Program
{
static void Main()
{
object obj = GetObject();
string str;
if (obj != null && GetString(out str))
System.Console.WriteLine(obj + str);
}
static object GetObject() => "hello"
static bool GetString(out string str)
{
str = "goodbye";
return true;
}
}

There's no problem here. C# knows that Main's 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.

External Content
Source RSS or Atom Feed
Feed Location http://ericlippert.com/feed
Feed Title Fabulous adventures in coding
Feed Link https://ericlippert.com/
Reply 0 comments