titaniumshovel titaniumshovel - 4 months ago 12
C# Question

Visual Studio Code Analysis - CA1804 thrown when variable is being used

I'm using VS2015 on Windows 7.

Code analysis rule CA1804 (http://msdn.microsoft.com/library/ms182278.aspx) states that I am not using a variable and to remove it. However, I am using this variable further down in my code. This is happening across the whole solution in hundreds of places. The code block looks like this:

[WebMethod]
public bool ValidateUser(string userName, string password)
{
string soapResult = String.Empty;
try
{
// code here
using (StreamReader rd = new StreamReader(responseStream))
{
soapResult = rd.ReadToEnd();
}
// code here
bool isValidated = true;
}
catch (Exception e)
{
// throw error
}

return isValidated;
}


I'm getting this error from Code Analysis:

Error CA1804 'ValidateUser(string, string)' declares a variable, 'soapResult', of type 'string', which is never used or is only assigned to. Use this variable or remove it.

Is there something I'm missing here? It's not within an if/else like some of the instances I'm getting this error. But I figured that if it's being used at all this error would not be thrown.

Thanks for any help.

Answer

Read the analysis message carefully, note the bit I have highlighted:

Error CA1804 'ValidateUser(string, string)' declares a variable, 'soapResult', of type 'string', which is never used or is only assigned to. Use this variable or remove it.

It is telling you that you only assign a value to it (you actually do that twice including the initialisation to string.Empty) but you never use the value. So it's effectively a waste of a variable.

What you should be doing is either using the value, for example:

soapResult = rd.ReadToEnd();
if(soapResult.Contains("something")
{
    isValidated = true;
}
else
{
    //Not needed but added it to better show how this works in context
    isValidated = false;
}

Or remove it altogether and discard the result you get from the StreamReader:

rd.ReadToEnd();
Comments