I'm making an initial assignment to my reference-type variable inside an awaited lambda, like so:
private class TestClass {
public int TestInt;
}
public async Task TestMethod() {
TestClass testVar;
await Task.Run(() => {
testVar = new();
});
var testInt = testVar.TestInt;
}
However, the last line gives the error "Use of unassigned local variable 'testVar'". Is there a technical reason why C#'s code analysis can't figure out that the variable is guaranteed to be assigned by that point? It's kind of annoying to have the use the !
operator wherever I first use testVar
. Is there any way to work round this if I need to first assign the variable inside an awaited lambda, and can't conveniently give it a default assignment (it's quite a complex class)?
It appears this is not an async/await issue but a general issue with lambda expressions. The compiler doesn't seem to be able to follow the path of the lambda to detect the assignment.
This code also doesn't compile:
So I first thought the compiler was generally unable to track assignments over method boundaries, but the following code surprisingly is ok:
So this appears to be some limitation of the compiler regarding lambda functions, but why - I cannot tell.