0

I have a ServiceField class which contains FieldId and Value as two properties .

    public class ServiceField
    {
        public int FieldId { get; set; }
        public string Value { get; set; }         
    }

        /// <summary>
        /// This method is used to assign value to HajjPackageFields class
        /// </summary>
        /// <param name="hajPackageObj">HajjPackageFields whose value needs to be updated</param>

        private void UpdateDetailFieldsValue(HajjPackageFields hajPackageObj)
        {
            foreach (ServiceField field in GetPackageDetails(hajPackageObj.PackageId))
            {

                if (field.FieldId == (int)HajjServiceFieldsEnum.AccomodationView)
                {
                    hajPackageObj.AccomodationView = field.Value == "1";
                }
                else if (field.FieldId == (int)HajjServiceFieldsEnum.AirTicket)
                {
                    hajPackageObj.AirTicket = field.Value == "1";
                }
            }
        }

Problem is if any new property add in HajjPackageField class than i have to modify my UpdateDetailFieldsValue method which is against the open close principle. Is there any other proper way to achieve this task ?

piet.t
  • 11,718
  • 21
  • 43
  • 52
shujaat siddiqui
  • 1,527
  • 1
  • 20
  • 41

1 Answers1

1

If I clearly understood you, reflection will help to solve problem:

private void UpdateDetailFieldsValue(HajjPackageFields hajPackageObj)
{
    var pairs = new Dictionary<int, string>();            
    foreach (var enumVal in typeof(HajjServiceFieldsEnum).GetEnumValues())            
        pairs[(int)(HajjServiceFieldsEnum)enumVal] = typeof(HajjServiceFieldsEnum).GetEnumName(enumVal);            

    foreach (ServiceField field in GetPackageDetails(hajPackageObj.PackageId))      
        typeof(HajjPackageFields).GetProperty(pairs[field.FieldId])
            ?.SetValue(hajPackageObj, field.Value == "1");  
}
Slava Utesinov
  • 13,410
  • 2
  • 19
  • 26