Reputation:
I have a two methods that are equivalent to this (pardon the contrived example):
public void WithResource(Action<Resource> action) {
using (var resource = GetResource()) {
action(resource);
}
}
public void Test() {
int id;
SomeObject someObject;
WithResource((resource) => {
id = 1;
someObject = SomeClass.SomeStaticMethod(resource);
});
Assert.IsNotNull(someObject);
Assert.AreEqual(id, someObject.Id);
}
(There's some more logic in the WithResource call I'm trying to factor out.)
I'm getting Use of unassigned local variable
compile-time errors because the assertions
are... using unassigned variables. I'm currently avoiding the issue by assigning them -1 and null
respectively.
Initializing to null
doesn't feel bad, but I'd like to avoid putting the -1 in there... I would really like to tell the compiler "trust me, this will become initialized". Since it's a test, I don't actually care too much if it bombs, because that only means I'll have to fix the test.
I'm tempted to ask if there's a way to give that hint to the compiler, but have the feeling that's even uglier. Does such a hint exist or should I just initialize the variables like I'm doing now?
Upvotes: 6
Views: 2241
Reputation: 660138
The other answers are correct. The easiest way to solve this problem is to initialize the locals.
I assume that you understand why the error is being produced: the compiler has no ability to know that the method called actually runs the lambda, and therefore no knowledge that the locals are initialized.
The only way to trick the compiler into not checking whether a variable is assigned is to make the variable non-local:
public void Test() {
int[] id = new int[1];
SomeObject[] someObject = new SomeObject[1];
WithResource((resource) => {
id[0] = 1;
someObject[0] = SomeClass.SomeStaticMethod(resource);
});
Assert.IsNotNull(someObject[0]);
Assert.AreEqual(id[0], someObject.Id);
}
Now you might say, well here I've clearly assigned id
. Yes, but notice that the compiler does not complain that you've used id[0]
before initializing it! The compiler knows that array element variables are initialized to zero.
Upvotes: 3
Reputation: 223277
Compiler is not smart enough to determine if the assignment would be made and hence the error.
You can't do anything about it, You have to assign it some default value, probably 0
,-1
, default(int)
or int.MinValue
Upvotes: 7
Reputation: 738
You should initialize the variables. The compiler will never trust you ;)
Upvotes: 3