Sak Sak - 2 months ago 12
C# Question

Assign bool value to a property when name of that property is present in another array

This is best I could make the question statement. Please be kind.

Here is the situation:

I have a string "InputValues" which contains values in comma seperated format:
chkAwareness1,chkAwareness2,chkAwareness6,chkAwareness9,chkAwareness13...

I need to fill an object with bool value if the name matches with what I have in above string variable.

example:
if InputValues contains "chkAwareness1" then "public bool chkAwareness1" should set to true, otherwise false.


public class SurveyCheckBox
{
public bool chkAwareness1 { get; set; }
public bool chkAwareness2 { get; set; }
public bool chkAwareness3 { get; set; }
public bool chkAwareness4 { get; set; }
public bool chkAwareness5 { get; set; }
public bool chkAwareness6 { get; set; }
public bool chkAwareness7 { get; set; }
.
.
.
}

public void createObjectSurveyCheckBox(string InputValues)
{
string[] ChkValues = InputValues.Split(',');
SurveyCheckBox surveyChkBoxObj = new SurveyCheckBox();
for (int i = 0; i < NumberOfPropertyInSurveyCheckBox ;i++ )
{
// typeof(SurveyCheckBox).GetProperties()[i].Name
}
}


I searched and I found GetProperties method through which I can get the name of property, but I am unable to figure out the logic.. how to search through the values and assign them to bool properties.

Please help.

Answer

You're very close. You just need to change your loop, really. The whole method should look like this:

public void CreateObjectSurveyCheckBox(string inputValues)
{
    string[] chkValues = inputValues.Split(',');
    SurveyCheckBox surveyChkBoxObj = new SurveyCheckBox();
    foreach (string value in chkValues)
    {
        PropertyInfo propInfo = typeof(SurveyCheckBox).GetProperty(value);
        if (propInfo != null)
            propInfo.SetValue(surveyChkBoxObj, true);
    }
}

P.S. You'll notice I took the liberty of changing your capitalization to something much more standard. If you use capitalization like you had, you're likely to get lynched.

Comments