Home > Back-end >  Wish to change a string[] variable depending on an int value
Wish to change a string[] variable depending on an int value

Time:10-06

i am new to c# and i have been trying to make a string[] that changes its contents depending on the int value of a different variable. i've tried switches and ifs but when i try to call the variable afterwards the program states that the variable does not exist in current context. Im sorry for the bad description but here's a sample code regarding what i mean.

 int flag = 0; //Value Changes
        if (flag == 1)
        {
            string[] mainoptions = {"Return"};
        }
        else if (flag == 0)
        {
            string[] mainoptions = { "Grab Shovel", "Return" };
        }
        WriteLine(mainoptions); //The name 'mainoptions' does not exist in current context

CodePudding user response:

For the vast majority of cases, any variables (eg. string name; or string name = "Roger";) that are created inside curly braces { } can only be accessed using their identifier from inside those braces.

Take this example:

int a = 0;
if (condition)
{
    int b = 1;
}
Console.WriteLine(a); // can see the 'a' variable -> works fine
Console.WriteLine(b); // can NOT see the 'b' variable -> compilation error

The variable a can be accessed from the "main scope" (for lack of a better term), and also inside the if statement because the if statement defines a sub-scope, per se.

Variable b however, can only be accessed from within the if statement it was declared in, and also any sub-scopes that might occur inside there. It can NOT be accessed outside that if statement, because as soon as the program exits the block (reaches the closing brace }) you can imagine that variable b's reference is deleted.

With that, you can edit your program to define the variable mainoptions outside the if statements, and that will solve your issue

CodePudding user response:

Let's get to the bottom of this: You didn't declare a variable/property behind the if-construction. Anything that is declared in a logical construct does not exist for the compiler behind it. You've probably seen this before in the "access level" here: link. If you want to print the variable array in a logical construct, you should do it like this:

if (a == someValue1)
{
  string[] b = { "Return" };
  System.Console.WriteLine(b);
}
else if (a == someValue2)
{
  string[] b = { "Grab Shovel", "Return" };
  System.Console.WriteLine(b);
}

But there's a mistake here: you can't assign something to an array just in curly braces { }, you have to declare it correctly:

string[] arr; // array is not initialized
arr = new string[] { "text", "text", "text" } // the array is now initialized

But that's not really convenient and the code gets bloated, so you should define this variable before the logical construct:

string[] b = new string[] { };

if (a == someValue1)
{
  b = new string[] { "Return" };
}
else if (a == someValue2)
{
  b = new string[] { "Grab Shovel", "Return" };
}

System.Console.WriteLine(b);

That's more convincing, isn't it? Now let's think what we can improve here...

  • The flag variable is of type int, but it takes 0 and 1, which is more like a bool, so let's make it a bool.
  • Flag can still be made a property to make it easier to use, let's do that!
  • Let's replace if-else with a switch-case, so there are no unnecessary checks.

And we get the following:

  class Program
  {
    public static bool Flag { get; set; }
    public static void Main(string[] args)
    {
      string[] mainoptions = new string[] { };

      Flag = false;

      switch (Flag)
      {
        case true:
          mainoptions = new string[] { "Return" };
          break;
        case false:
          mainoptions = new string[] { "Grab Shovel", "Return" };
          break;
      }

      foreach (var option in mainoptions)
        System.Console.WriteLine(option);
    }
  }

Oh, did you also notice that I printed the result differently, and there is a new foreach construct?

foreach (var option in mainoptions)
        System.Console.WriteLine(option);

Well, you can't just print the array because you just get its type, not its content. To print the whole array, we have to go through it from index 0 to the end, printing out every value. You can address the array using the index:

var arr = new int[] { 1, 2, 3, 4 };
Console.WriteLine(arr[0]); // => print 1

Let's make it even cooler, shall we? We use a ternary operator, it's an analogue of if-else when we only have 2 execution paths:

class Program
{
  public static bool Flag { get; set; }
  public static void Main(string[] args)
  {
    string[] mainoptions = new string[] { };

    Flag = false;

    mainoptions = Flag ? new string[] { "Return" } : new string[] { "Grab Shovel", "Return" };

    foreach (var option in mainoptions)
      System.Console.WriteLine(option);
  }
}

I hope this will be useful! Have a nice day!

CodePudding user response:

You need to declare out side the if condition:

        int flag = 0; //Value Changes
        string[] mainoptions=null;
        if (flag == 1)
        {
             mainoptions = {"Return"};
        }
        else if (flag == 0)
        {
            mainoptions = { "Grab Shovel", "Return" };
        }
        WriteLine(mainoptions); // now this will be work for you

CodePudding user response:

so what i have learned you can use a If to check a var! you can also use a switch statement witch are super useful!

int Flag = 0;
String mainoptions;
Static void Main()
{
   switch(Flag)
   {
     case 1:
     // case means the if this is the var then run this block of code.
     // the 1 is the int number so if we put 100 in the place of the 1 then the switch statment would check if the var (Flag) is 100. and if it the code just moves on. you can add whatever you want in the case 1. so if you wanted your string to be "Example" if the int Flag was 1 then you would put: 
     mainoptions = "mainoption's";
     // you can as as many cases as you want as well. 
     Brake;
   }
}

also your mainoptions does not exist bc its a temp var. your int Flag works bc its outside of the method AKA in the class. so in other words you cant use temp vars outside of the method it is put into or initialised in.

CodePudding user response:

Outside of implementing collections yourself, arrays are generally a poor choice for storing a collection of objects. Consider instead using List<string>:

int flag = 0; //Value Changes
var mainOptions = new List<string>{
    "Return"
};
if (flag == 0)
    {
        mainoptions.Insert(0,"Grab Shovel");
    }
WriteLine(mainoptions);

(If WriteLine is your own method, you may have to change its signature to accept List<string> instead of string[] and there may be further cascading changes)

Part of what makes arrays awkward to work with is that they have a fixed number of elements. But you're already working in a scenario where you want to easily change the number of elements. So use a type that makes that easy to do.

  •  Tags:  
  • c#
  • Related