Error with local variable

The following function generates an error: “Using the unassigned local variable“ intLast. ”I'm not sure what I'm doing wrong.

static string RemovePath(string strInput) { int intLast; for (int i = 1; i < strInput.Length; i++) { if (strInput.Substring(i, 1) == @"\") { intLast = i; } } string strOutput = strInput.Substring(strInput.Length - intLast); return strOutput; } 
+4
source share
7 answers

You use the intLast variable in the following line:

 string strOutput = strInput.Substring(strInput.Length - intLast); 

But the variable will only matter under certain conditions ( strInput.Length > 1 and strInput.Substring(i, 1) == @"\" ). therefore a mistake.

To resolve this issue, specify a default value for the ad:

int intLast = 0; // or any default value.

+2
source

Initialize intLast with some value, because the loop cannot guarantee that the value is assigned, because the execution of the loop is determined at runtime.

  int intLast = 0; 

The following lines request an unassigned variable because the control may not go into a loop to assign a value.

 string strOutput = strInput.Substring(strInput.Length - intLast); 
0
source

Since you assign intLast only inside a conditional expression, from the point of view of the compiler, you can use it without initializing it.

You should initialize it to some default value at the beginning, even if you do not expect to ever use it.

 int intLast = 0 
0
source

You need to set the default value to intLast .

Try the following:

 static string RemovePath(string strInput) { int intLast = 0; for (int i = 1; i < strInput.Length; i++) { if (strInput.Substring(i, 1) == @"\") { intLast = i; } } string strOutput = strInput.Substring(strInput.Length - intLast); return strOutput; } 
0
source

Just change :

 int intLast = 0; 

All code will look like this:

static string RemovePath (string strInput) {int intLast = 0;

  for (int i = 1; i < strInput.Length; i++) { if (strInput.Substring(i, 1) == @"\") { intLast = i; } } string strOutput = strInput.Substring(strInput.Length - intLast); return strOutput; } 

You just need to set intLast to zero.

0
source

You must initialize your intLast variable.

The compiler does not know that a variable of type intLast will be assigned no matter what.

  int intLast = 0; 
0
source

You must initialize your variable as

 int intLast = 0; 

Because it can remain unassigned if the code does not reach the if condition.

0
source

All Articles