Taylor Stevens
Taylor Stevens

Reputation: 95

C# Checking a variable against a arrays index?

Sorry if the title isnt clear enough, But heres my problem.

so i have this array:

public static string[] stringArray = new string[3] {"Menu", "Options", "Exit"};

and this variable:

public static int pointerLocation = 0;

now my end goal is to check if eg if pointerLocation is equal to any index of the array. to then print > infront of the "selected" item or current index.

My problem is when im checking if pointerLocation == stringArray[0] i am of course faced with the problem of not being able to compare string and int's.

So what can i do to work around this?

EDIT:

Heres exactly what im trying to do. Im trying to create a Menu in the console and i want the user to want to be able to see whats selected so it will look like this:

> Start
Options
Exit

And i want the > to be printed on the lne where the index of the item in the array is equal to my variable pointerLocation, If that makes sense?

Also the pointerLocation variable will be incrementing/decrementing as the up/down arrows are pressed

Upvotes: 0

Views: 194

Answers (3)

Jonik
Jonik

Reputation: 1249

If you want to compare index of any value in array, so it's simply:

public static string[] stringArray = new string[3] {"Menu", "Options", "Exit"};
public static int pointerLocation = 0;
if(pointerLocation==Array.IndexOf(stringArray, "Menu"))
{
   Console.WriteLine(stringArray[pointerLocation]);
}

But if array contains more than one values, so function returns only first index of matched values.

Upvotes: 0

vidstige
vidstige

Reputation: 13079

I guess something like this will help

for (int i = 0; i < stringArray.Length; i++)
{
    if (i == pointerLocation)
    {
        Console.WriteLine("> " + stringArray[pointerLocation]);
    }
    else
    {
        Console.WriteLine(stringArray[pointerLocation]);
    }
}

Let me suggest some variable renames

  • stringArraymenuItems
  • pointerLocationselected

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You could test if the pointerLocation index is strictly smaller than the size of the array before accessing it:

if (pointerLocation < stringArray.Length)
{
    // You can access and use the value at the specified index safely here
    string value = stringArray[pointerLocation];
    Console.WriteLine(value);
}

Upvotes: 0

Related Questions