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 specifying ref
but it does not yet have a value. That is not legal, as VerifySomeStuff
could choose to read the value, which does not have a defined value at this point. Assigning null
satisfies the definite assignment requirement. An alternative would be out
:
string errorMessage;
bool isOK = SomeClassWithBusinessRules.VerifySomeStuff(id, out errorMessage);
if (!isOK)
throw new BusinessException(errorMessage ?? "Some error occured.");
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 for VerifySomeStuff
to assign null
to 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:
string errorMessage = SomeClassWithBusinessRules.VerifySomeStuff(id);
bool isOK = errorMessage == null;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With