Clarification of question: I am not looking for answers on how to solve this issue (several are listed below), but as to why it is happening.
I expect the following code to compile:
struct Alice
{
public string Alpha;
public string Beta;
}
struct Bob
{
public long Gamma;
}
static object Foo(dynamic alice)
{
decimal alpha;
long beta;
if (!decimal.TryParse(alice.Alpha, out alpha) // *
|| !long.TryParse(alice.Beta, out beta)) // **
{
return alice;
}
var bob = new Bob { Gamma = beta }; // ***
// do some stuff with alice and bob
return alice;
}
However the following compile time error is thrown at // ***
:
Use of unassigned local variable 'beta'
I can make the program compile under the following situations:
If I change the signature to be
static object Foo(Alice alice)
Explicitly casting on the lines
// *
and// **
, e.g.:!long.TryParse((string)alice.Beta, out beta)
.Removing the
decimal.TryParse
on line// *
.Replacing the short circuit or
||
with|
. Thanks to HansPassantSwapping the
TryParse
s aroundPulling the results of the
TryParse
s intobool
s Thanks to ChrisAssigning a default value to
beta
Am I missing something obvious, or is there something subtle going on, or is this a bug?