Reputation: 835
Here is the text file
country1: 93#country2: 355#country3: 213#country4: 376#country5: 244#country6: 54#country7: 374#
For this ASP.NET web services,when i declare string temp ouside "for" loops, Error "Use of unassigned local variable 'temp'"
[webMethod]
public string[] getContryCode ()
{
string temp;
string[] data = File.ReadAllLines(@"countryCode.txt");
string[] country = data[0].Split('#');
for (int i = 0; i < country.Length; i++ )
{
temp = country[i];
}
//const string f = "countryCode.txt";
return temp.Split(':');
}
If i declare string temp inside a loop,i can't return a value of "temp.Split(':')". Need find a way to solve it
originl file format: #country1:code1#country2:code2#
array list 'country': [0] country1 code1 country2 code2
- i can get this work b split
temp.split(':') : should get things like this [0]country1 [1] code1 [2] country2 [3] code2
Upvotes: 0
Views: 990
Reputation: 25855
Your for loop is not guaranteed to iterate once, so you are getting a compiler error that temp may not have a value when you attempt to use it.
Try:
string temp = "";
Even better, though, would be to add proper testing to ensure that all of your inputs are as expected:
if ( !System.IO.File.Exists( @"countryCode.txt" ) )
throw new ApplicationException( "countryCode.txt is missing" );
string[] data = File.ReadAllLines(@"countryCode.txt");
if ( data.Length == 0 )
throw new ApplicationException( "countryCode.txt contains no data" );
if ( data[0].Length == 0 )
throw new ApplicationException( "malformed data in countryCode.txt" );
string[] country = data[0].Split('#');
string temp = "";
for (int i = 0; i < country.Length; i++ )
{
temp = country[i];
}
return temp.Split(':');
I am not really sure what you are trying to accomplish with the for-loop, though, since you are only going to be returning the last item in the country array, which would be the same as: return country[country.Length - 1];
EDIT:
You may want to remove empty entries in your country
array. You can just use the RemoveEmptyEntries option:
string[] country = data[0].Split('#', StringSplitOptions.RemoveEmptyEntries);
/* Using the RemoveEmptyEntries option can cause the function to
return a 0-length array, so need to check for that afterall: */
if ( country.Length == 0 )
throw new ApplicationException( "malformed data in countryCode.txt" );
Upvotes: 5