I'm curious why both of the following code segments produces error CS0165: Use of unassigned local variable 'i':
// Attempt #1
object obj = 4;
bool isInt = obj is int i;
if (isInt)
Console.WriteLine("obj = {0}", i); // CS0165
// Attempt #2
object obj = 4;
bool isInt;
if (isInt = obj is int i)
Console.WriteLine("obj = {0}", i); // CS0165
The following compiles, but seems like it shouldn't be necessary:
object obj = 4;
bool isInt = false;
if (obj is int i)
{
isInt = true;
Console.WriteLine("obj = {0}", i);
}
Is there a less verbose way to use C# Declaration and Type Patterns when attempting to store the result of the test condition?
ifstatement. Like:object obj = 4; if (obj is int i) { Console.WriteLine("obj = {0}", i); // perform other logic here for the int value }