Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to pass property dynamically in a object model in for each loop in c#. error – Identifier expected

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");
}
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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");
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading