I am trying to access a string outside the using statement whose value is assigned inside a using statement as shown below.
I get an error "Use of unassigned local variable 'savedUrl'".
customItem.name = ld.Name;
customItem.Location = new GeoCoordinate(ld.Latitude, ld.Longitude, 0);
string savedUrl;
using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
{
if (iso.FileExists(string.Format("{0}.jpeg", ld.Title)))
{
savedUrl = string.Format("{0}.jpeg", ld.Title);
}
}
addSignPosts();
addLabel(ARHelper.AngleToVector(customItem.Bearing, WCSRadius), customItem.name, savedUrl);
As you can see, I declared the string 'savedUrl' outside the using statement so that it will have a scope outside the using statement. But it seems that I cannot access it when it is being assigned inside the using statement.
I tried changing it to a global variable. But it isnt working and it is a bad practice too.
So what I am supposed to do ? Am I missing something here ?
Or is there any workaround for this ?
Well yes - if iso.FileExists(string.Format("{0}.jpeg", ld.Title))
returns false then you won't be assigning a value to savedUrl
. What value do you want savedUrl
to have in that case? This has nothing to do with the using
statement - it's only about the if
statement.
For example, if you want the value to be null
if the file doesn't exist, you could reverse the logic and assign it the "candidate" value first, setting it to null if the file doesn't exist:
string savedUrl = string.Format("{0}.jpeg", ld.Title);
using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!iso.FileExists(savedUrl))
{
savedUrl = null;
}
}
Or perhaps use the conditional operator:
string savedUrl;
using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
{
string candidateUrl = string.Format("{0}.jpeg", ld.Title);
savedUrl = iso.FileExists(candidateUrl) ? candidateUrl : null;
}
Note how in both of these snippets, I've changed the code to only call string.Format
in one place - that makes it easier to change the code consistently later.
See more on this question at Stackoverflow