1

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?

1
  • Depending on what you need the result of the test condition for, you can skip the assignment of the boolean entirely and just perform your logic in your if statement. Like: object obj = 4; if (obj is int i) { Console.WriteLine("obj = {0}", i); // perform other logic here for the int value } Commented Sep 29, 2022 at 16:55

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.