I have this following code:
I get the error, "Use of un-Assigned Local variable"
I'm sure this is dead simple, but im baffled..
public string return_Result(String[,] RssData, int marketId)
{
string result;
foreach (var item in RssData)
{
if (item.ToString() == marketId.ToString())
{
result = item.ToString();
}
else
{
result = "";
}
}
return result;
}
Initialize result when you declare it. If the collection is empty neither of the branches of the if statement will ever be taken and result will never be assigned before it is returned.
If
RssData
has zero items, the loop will not run, leavingresult
undefined. You need to initialize it to something (e.g.string result = "";
) to avoid this error.That is because the compiler can't know that there always are any items in
RssData
. If it would be empty, the code in the loop would never be executed, and the variable would never be assigned.Just set the variable to null when you create it, so that it always has a value:
If there are no items in
RssData
, thenresult
will have never been set, and thus invalid.Either initialize
result
(e.g.,string result = null;
) or consider that in your design by checking for emptiness, and setting or returning a failure state in that scenario.Change your line from
To
The compiler is just saying "Hey, you are using result and it has not been assigned yet!". This even ocurrs when you are assigning it for the first time, if you're not doing so in the initial instantiation.
You will also want to consider how you need to handle your code if you return an empty string, due to your array argument being passed in empty. You could choose to return an empty string, or a null value. This is just a behaviorial decision.
This can happen for all variable types as well.
For collections and objects, initialize using new.
eg.
List<string> result = new List<string>();