0

I have created a public class, Applicant. I have created a new Applicant object on my code and I want to loop through each of the properties of the applicant class. I am using the code below, however I am getting the error: "Object does not match target type." Thanks for your help

public class Applicant
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string JobTitle { get; set; }
    public string Company { get; set; }
    public string Email { get; set; }
    public string TelephoneNumber { get; set; }
    public string LinkedIn { get; set; }
    public string Website { get; set; }
    public string Instagram { get; set; }

    public Applicant(string _firstname, string _lastname, string _jobtitle, string _company, string _email,
        string _telephonenumber, string _linkedin, string _website, string _instagram)
    {
        Firstname = _firstname;
        Lastname = _lastname;
        JobTitle = _jobtitle;
        Company = _company;
        Email = _email;
        TelephoneNumber = _telephonenumber;
        LinkedIn = _linkedin;
        Website = _website;
        Instagram = _instagram;
    }
}
    //Create a new Applicant object
    Applicant applicant = new Applicant(Firstname.Value, Lastname.Value,
    JobTitle.Value, Businessname.Value, Email.Value, TelephoneNumber.Value, Linkedin.Value, Companywebsite.Value, Instagram.Value);

    PropertyInfo[] properties = applicant.GetType().GetProperties();
    foreach (var p in properties)
    {
    Response.Write(p.GetValue(properties, null).ToString());
    }
Amir Ali
  • 417
  • 5
  • 10
  • This may be an XY problem (https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Please elaborate what you want to achieve with that – Sebastian L Feb 13 '19 at 14:06

2 Answers2

0

The target object here is the applicant, not the array of properties:

Response.Write(p.GetValue(applicant, null).ToString());

also: watch out that the property value could be null, so you might prefer:

Response.Write(Convert.ToString(p.GetValue(applicant, null)));
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

You need to pass the object you're trying to get the property value for into the GetValue method. However, you're passing the property collection instead.

Instead of doing

Response.Write(p.GetValue(properties, null).ToString());

You should be doing

Response.Write(p.GetValue(applicant, null).ToString());
Imantas
  • 1,621
  • 13
  • 19