0

First time on stackOverflow, so this might be a really nooby question, but i was wondering if i could change multiple variable values at the same time without having to write out every single one.

Here is my code at the moment:

public string Label1Text()
{
    int index;

    for (index = 0; index < 32; index++)
    {
        if (seatChosen[index])
        {
            _bookedSeats += "A" + (index + 1) + " ";
            Properties.Settings.Default.A1 = true;
        }
    }

    string text = _bookedSeats + ".";

    //debug
    label1.Text = text;

    return text;
}

The line

Properties.Settings.Default.A1 = true; 

is what i want to change to something like this (theoretical code)

Properties.Settings.Default.A[index] = true; 

or

Properties.Settings.Default.A + index = true;

I hope you can understand what I'm trying to accomplish.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
  • Simple answer: you can't. – abatishchev Oct 22 '15 at 22:08
  • Less simple answer: You could use reflection, but it's probably more effort than it's worth. – Dave Zych Oct 22 '15 at 22:09
  • In your case, you could switch to an actual dictionary in your settings as discussed here: http://stackoverflow.com/questions/922047/store-dictionarystring-string-in-application-settings – Av Pinzur Oct 22 '15 at 22:26
  • Check this post , you can use `Dictionary` instead. http://stackoverflow.com/questions/20857773/create-dynamic-variable-name – Mironline Oct 22 '15 at 22:26
  • It seems like you are coding this in an odd way. Why are you defining all of the `A1`, `A2`, `A3`, etc, variables in the first place? Why not use an array? – Enigmativity Oct 23 '15 at 00:58

1 Answers1

0

Using reflection: (I'm assuming Properties.Settings.Default is a static class, and A1, A2, etc. are public static properties.)

Type type = typeof(Properties.Settings.Default);
var prop = type.GetProperty(index.ToString("\\A0"));
if (prop != null)
    prop.SetValue(null, true);

If Default is an instance, you would need to pass it to SetValue instead of null. Also, C# v6 allows a more concise syntax.

Type type = Properties.Settings.Default.GetType();
type.GetProperty($"A{index}")?.SetValue(Properties.Settings.Default, true);
tremas317
  • 81
  • 1
  • While this does answer the question, I wouldn't recommend this approach unless you are dealing with properties that are unknown at compile time. IMHO, this a warning that the structure of your code needs to be looked at. I certainly wouldn't want to see any of my team using something as heavy as reflection just to save manually typing a few extra lines. – Ahhhhbisto Oct 23 '15 at 22:07