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?