Home > database >  how to pass property dynamically in a object model in for each loop in c#. error - Identifier expect
how to pass property dynamically in a object model in for each loop in c#. error - Identifier expect

Time:08-08

How to pass item of list of string into a foreach loop in C# as a object property dynamically . giving error - identifier expected. objectModel is class with below defined parameters;

public class objectModel(){
 public string fname{get;set;}
 public string lname{get;set;}
}


string[] mandatoryFields ={'fname,lname'};

objectModel.fname="ABC";
objectModel.lname="XYZ"


foreach(var field in objectModel)
{
if(objectModel.[field] ==null)//getting error here
{
Console.Write("Invalid Field");
}
}

CodePudding user response:

Here is the implementation with reflection:

var objectModel = new ObjectModel();
var mandatoryFields = new List<string> { "fname", "lname" };

foreach (var prop in objectModel.GetType().GetProperties())
{
    if (mandatoryFields.Contains(prop.Name))
    {
        if (prop.GetValue(objectModel) == null)
           Console.WriteLine("Invalid Field");
    }
}
  • Related