'Is there a way to use a string to reference a variable by name?

I am trying to find a better way to populate 100+ variables and notify the UI with OnPropertyChanged() that the variable has changed. Also I do not feel that a DataGrid is a good solution from a presentation perspective.

Is there a better way or pattern to use?

private string fred;
private string wilma;
public string Fred
{ 
    get { return fred; } 
    set { fred = value; OnPropertyChanged("Fred"); }
}
public string Wilma
{ 
    get { return wilma; } 
    set { wilma = value; OnPropertyChanged("Wilma"); }
}
public void set_value(string name, string val)
{
   switch (name)
   {
      case "Fred": Fred = val; break;
      case "Wilma": Wilma = val; break;
   }
}

What I would like to do is something like:

private string fred;
private string wilma;
public string GenericMagic(string name)
{ 
    get { return magicSmoke(name); } 
    set { magicSmoke(name) = value; OnPropertyChanged(name); }
}
public void set_value(string name, string val)
{
   GenericMagic(name) = val;
}

I can imagine it, but does something like this exist? I am writing in C#, XAML for a UI.

Thank you in advance.



Solution 1:[1]

You can use reflection for that, create the set_value method the following way:

public void set_value(string name, string val)
{
    var propertyInfo = GetType().GetProperty(name);
    propertyInfo.SetValue(this, val);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fbede