Use of unassigned variable in C# 10

Viewed 93

Consider the following code under .NET 6, C# 10:

bool isAggregate;
var exception = new Exception();
if (isAggregate = exception is AggregateException aggregateException)
{
    foreach (var innerException in aggregateException.InnerExceptions)
    {
    }
}

The compiler complains that aggregateException is unassigned here. I would think that this way of declaring a variable name within a condition should have worked. Is this a corner case or am I missing something?

Removing the assignment expression from the condition seems to work just fine:

if (exception is AggregateException aggregateException)

EDIT: Another odd case as I was trying to get used to new language features:

public Error (Exception exception)
{
    if (exception.InnerException is null innerException) // Error.
    {
    }
}

I have gotten used to if (int.TryParse("0", out var i)) { } so was surprised that there wasn't a concise way to declare variables inline this way.

Error 1:

Error 2:

0 Answers
Related