2

I have a class

public class ProjectTask
{
    public ProjectTask();


    [XmlElement("task_creator_id")]
    public string task_creator_id { get; set; }
    [XmlElement("task_owner_id")]
    public string task_owner_id { get; set; }
    [XmlElement("task_owner_location")]
    public TaskOwnerLocation task_owner_location { get; set; }
    [XmlElement("task_owner_type")]
    public string task_owner_type { get; set; }
    [XmlElement("task_type_description")]
    public string task_type_description { get; set; }
    [XmlElement("task_type_id")]
    public string task_type_id { get; set; }
    [XmlElement("task_type_name")]
    public string task_type_name { get; set; }
}

An xml will be deserialized to this at runtime.

Is there way to get the field name and value?

Using reflection I can get the property names like so:

PropertyInfo[] projectAttributes = typeof(ProjectTask).GetProperties();

A foreach loop can be applied to get the properties

foreach(PropertyInfo taskName in projectAttributes)
       {
           Console.WriteLine(taskName.Name);
       }

but how do I print the property and the value? Like task_creator_id = 1

where task_Id is one of the properties and the value of that at runtime is 1.

1

2 Answers 2

1

Use taskName.GetValue(yourObject,null)

where yourObject should be of an instance of ProjectTask. For ex,

ProjectTask yourObject = (ProjectTask)xmlSerializer.Deserialize(stream)

var propDict = typeof(ProjectTask)
                  .GetProperties()
                  .ToDictionary(p => p.Name, p => p.GetValue(yourObject, null));
1
  • Thanks L.B, that did the job.
    – Codehelp
    Commented Jul 24, 2012 at 10:49
1

You can do that using your PropertyInfo object :

var propertyName = MyPropertyInfoObject.Name;
var propertyValue = MyPropertyInfoObject.GetValue(myObject, null);

A foreach loop give you access to all properties of your type, you can also have a specefic property knowing its name, like so :

var MyPropertyInfoObject = myType.GetProperty("propertyName");
2
  • The foreach loop gets the name but gives Object does not match target type error
    – Codehelp
    Commented Jul 24, 2012 at 10:12
  • You can do a cast to the returned object
    – SidAhmed
    Commented Jul 24, 2012 at 10:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.