Use of unassigned local variable after going through a list

List <State> states = JsonConvert.DeserializeObject <List<State>> (json);

State state;
foreach(State i in states) {
if (i.StateID == Convert.ToInt32(extendedProperties["WFState"])) {
    state = i;
    } 
else {}
}

try {
    btnApprove.Visible = state.Actions.Approved.NextStateID != null ? true : false;
    btnApprove.Text = state.Actions.Approved.Title.ToString();
}
catch (Exception ex) {
    btnApprove.Visible = false;
}

"state" in "state.Actions.Approved.NextStateID != null ? true : false;" is giving the "use of unassigned local variable" even though it assigned.

Upvotes: 0

Views: 154

Answers (2)

Brian Rogers
Brian Rogers

Reputation: 129787

The state variable would be unassigned if:

  • the states list is empty, or
  • the condition if (i.StateID == Convert.ToInt32(extendedProperties["WFState"])) is false for all states in the list.

You need to initialize the state variable to null (or better yet a valid state value) to avoid the compiler warning.

Upvotes: 0

Jonathan
Jonathan

Reputation: 5018

What if states doesn't have anything in it? state might not be populated.

maybe something like:

List < State > states = JsonConvert.DeserializeObject < List < State >> (json);

if(!states.Any())
    return;

State state;
foreach(State i in states) {
if (i.StateID == Convert.ToInt32(extendedProperties["WFState"])) {
    state = i;
    } 
else {}
}

try {
    btnApprove.Visible = state.Actions.Approved.NextStateID != null ? true : false;
    btnApprove.Text = state.Actions.Approved.Title.ToString();
}
catch (Exception ex) {
    btnApprove.Visible = false;
}

Upvotes: 1

Related Questions