-2

I recently came up to the following Message with the code below

string errorMessage = String.Empty;

I've been getting:

Message IDE0059 Unnecessary assignment of a value to 'errorMessage'

The only place this is used was

var valid = IsValid(out errorMessage);

Why am I getting this Message?

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61

3 Answers3

3

Just don't set the initial value. This is perfectly valid code :

string errorMessage;
var valid = IsValid(out errorMessage);   

Or use

var valid=IsValid(out var errorMessage);

The compiler knows that the variable is used as an out parameter and will get a value unless an exception is thrown.

On the other hand, IsValid has to store a value in the out parameter, overwriting any initial value. The original value is never used, and so doesn't need to be assigned.

This won't compile :

public bool IsValid(out string errorMessage) {
   return true;
}

and return :

CS0177 The out parameter 'errorMessage' must be assigned to before control leaves the current method

This will work :

public bool IsValid(out string errorMessage) {
   errorMessage="";
   return true;
}
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
2

I don't think that message needs explanation, it basically says that the value that you've assigned to errorMessage is unnecessary, because you have never used that (errorMessage) variable.

In that case, if you never planning to use errorMessage variable, you can use one handy tool, called Discards, so you can write:

bool value = IsValid(out _);
SᴇM
  • 7,024
  • 3
  • 24
  • 41
0

The .net compiler forces us to assign a value to any out parameter in the function getting the variable with the out modifier.

So in the example below:

public bool IsValid(out string errorMessage) {
   return true;
}

We would get the error

Error CS0177 The out parameter 'errorMessage' must be assigned to before control leaves the current method ServicesUtils

Since it's mandatory to assign a value, the compiler is clever enough to warn us of a redundant assignment beforehand, which will be overriden in a mandatory way.

This way we are protected from being misled by the initial assignment.

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61