Brian Hudson Brian Hudson - 5 months ago 17
C# Question

How do I access an object outside of a subroutine?

I am taking IT at school and we have to build a basic program that compares 2 characters and tells the user which one is better.

I am using a basic GUI in a winform that uses a listbox to select the character you want to compare.

However, I need to call the

object in my if statement, in order to compare the totals.

public void lstbxCharacter1_SelectedIndexChanged(object sender, EventArgs e)
Character selectedCharacter = characters.ElementAt(lstbxCharacter1.SelectedIndex);

lblName1.Text = "Name: " + selectedCharacter.getName();
lblNinjutsu1.Text = "Ninjutsu: " + selectedCharacter.getNinjutsu();
lblGenjutsu1.Text = "Genjutsu: " + selectedCharacter.getGenjutsu();
lblTaijutsu1.Text = "Taijutsu: " + selectedCharacter.getTaijutsu();
lblIntellegence1.Text = "Intellegence: " + selectedCharacter.getIntellegence();
lblStrength1.Text = "Strength: " + selectedCharacter.getStrength();
lblSpeed1.Text = "Speed: " + selectedCharacter.getSpeed();
lblStamina1.Text = "Stamina: " + selectedCharacter.getStamina();
lblHandSigns1.Text = "Hand Signs:" + selectedCharacter.getHandSigns();
lblTotalValue1.Text = selectedCharacter.getTotal().ToString();
pb1.Image = Image.FromFile(selectedCharacter.getImage());


^Here is my subroutine to change characters by selecting the name from the listbox (Just ignore all the "get" methods)

public void displayWinner()
if ()
lblWinner.Text = "Character 1 is better";
else if ()
lblWinner.Text = "Character 2 is better";
lblWinner.Text = "These characters are equal";


^Here is my if statement. I am trying to make the condition something like
(selectedCharacter.getTotal() > selectedCharacter2.getTotal())
but cannot access the

So my question is, is there a way to access the
within the subroutine, or should I do this another way?

Thank you for your help,


A variable (such as selectedCharacter) cannot be used unless it is in scope for the code trying to access it. In C#, a set of {} creates a new scope. Code can access its own scope and any scope it is nested in.

Because the selectedCharacter variable is local to the IndexChanged method, it is not in scope for displayWinner. To fix it, move that variable into the class scope. Now both methods can access it:

Character selectedCharacter;
Character otherSelectedCharacter;

public void lstbxCharacter1_SelectedIndexChanged(object sender, EventArgs e)
    selectedCharacter = characters.ElementAt(lstbxCharacter1.SelectedIndex);

public void DisplayWinner()
   if (selectedCharacter.IsBetterThan(otherSelectedCharacter))

To avoid the case where DisplayWinner is called with no selection (and thus selectedCharacter.<anything> would throw a NullReferenceException), you can use a null conditional operator and null coalescing to automatically fail your check (among other ways, but this one is short and to the point).

if (selectedCharacter?.IsBetterThan(otherSelectedCharacter) ?? false)