Elim99
Elim99

Reputation: 673

C# Automatically linking strings to properties using the string value

This might be a stupid one but I'll shoot it out there.

For example let's say I have a model class:

public class PermissionModel
{
    public bool AppName_Home_Product_SaveButton_Enabled { get; set; }
    public bool AppName_Home_Product_ConfirmButton_Enabled { get; set; }
}

And I have the following list of strings:

"AppName_Home_Product_SaveButton_Enabled_true"
"AppName_Home_Product_SaveButton_Enabled_false"

I want to automatically populate the model properties with true/false without having to use if statements as in the following example:

if (aString.Contains("AppName_Home_Product_SaveButton_Enabled"))
{       
    PermissionModel.AppName_Home_Product_SaveButton_Enabled = Convert.ToBoolean(AString.Substring(AString.IndexOf("Enabled_") + 8));
}

Any ideas or is this crazy? I just want to avoid a bunch of if statements to populate the model and make it more re-usable.

Upvotes: 1

Views: 92

Answers (1)

JaredPar
JaredPar

Reputation: 755587

This can be done via reflection

const string delimiter = "_Enabled";
foreach (string data in aString) {
  int index = data.IndexOf(delimiter);
  if (index >= 0) {

    // Get the name and value out of the data string 
    string name = data.Substring(0, index + delimiter.Length);
    bool value = Convert.ToBoolean(data.Substring(index + delimiter.Length + 1));

    // Find the property with the specified name and change the value
    PropertyInfo  property = GetType().GetProperty(name);
    if (property != null) {
      property.SetValue(this, value);
    }
  }
}

Upvotes: 2

Related Questions