Click here to Skip to main content
15,886,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
Well I m new to Resharper tool, so just unaware how it derives upto certain suggestions.
So, for example, I declare a string variable and initialize it as :

C#
string str=string.empty;// here I get the "Remove redundant initializer

if (true)
{
str="True";
}
else
{
str="false";
}


The reason I m initializing

C#
str=string.empty;


is that because I don't want the compiler to assign any dummy/garbage values to the variable.

Please guide.
Thanks in advance

Now based on Abhinav's comment, I have improved the question with below:
But let us suppose, for instance,if I had only

C#
string str;
if (true)
{
}
else
{
str="false";
}

what value would then be in str??
Posted
Updated 8-Feb-15 22:15pm
v2

Lets understand Redundant Initialization first.

EXPLANATION
This variable's initial value is not used. After initialization, the variable is either assigned another value or goes out of scope.
Example: The following code excerpt assigns to the variable r and then overwrites the value without using it.
int r = getNum();  //Redundant
r = getNewNum(buf);


In your case, after the code runs, the value of str will be either True or False.
So you don't need to worry about garbage values.

Just remove string str=string.empty; and make it string str;
 
Share this answer
 
Comments
aryan_85 6-Dec-14 8:06am    
Thanks for the explanation Abhinav.
:-)
But let us suppose, for instance,if I had only

string str;
if (true)
{
}
else
{
str="false";
}

what value would then be in str??
M sorry for again bothering you..but just want to know inquire a bit more regarding it.
TheRealSteveJudge 9-Feb-15 4:22am    
Good. 5*
@aryan_85: if you do not assign anything then the value of str will be "null".
To answer the 2nd part of your amended question, as TheRealSteveJudge has pointed out the value of str would be null.

More importantly if you then tried to use str after this point you would get an error
Quote:
Error 2 Use of unassigned local variable 'str'
and resharper would not be telling you that a string str = string.empty is redundant.
Basically you should EITHER ensure that str is initialised OR ensure that all the code paths result in a value being assigned to str

Both Visual Studio and Resharper are helping you to both remove code that isn't necessary, and also helping you to find potential errors BEFORE you try to run your program.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900