This is something that I have wondered about for a while now. I have browsed a bunch of questions containing the error below in their title but couldn’t find one that explains this case.
First look at this example:
private void test() {
string errorMessage;
bool isOK = SomeClassWithBusinessRules.VerifySomeStuff(idOfStuffToVerify, ref errorMessage);
if (!isOK)
throw new BusinessException(errorMessage ?? "Some error occured.");
}
If you compile this the compiler will complain with this message:
Error 2 Use of unassigned local variable ‘errorMessage’
Changing the variable initializer to null will make it go away.
This will compile:
private void test() {
string errorMessage = null;
bool isOK = SomeClassWithBusinessRules.VerifySomeStuff(idOfStuffToVerify, ref errorMessage);
if (!isOK)
throw new BusinessException(errorMessage ?? "Some error occured.");
}
So why do we get the compilation error?
When you pass it to
VerifySomeStuff, you are specifyingrefbut it does not yet have a value. That is not legal, asVerifySomeStuffcould choose to read the value, which does not have a defined value at this point. Assigningnullsatisfies the definite assignment requirement. An alternative would beout:which would be legal (but requires changes to
VerifySomeStuff, since the signature must be changed and it is now required to assign a value to the parameter before exit (unless an exception occurs)). From the code shown, it you might choose forVerifySomeStuffto assignnullto the parameter if there is no error.Of course, if the bool and string then duplicate the “was there a problem” purpose, you could also use: