Codehelp
Codehelp

Reputation: 4787

Property and name at runtime from a class

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.

Upvotes: 2

Views: 2064

Answers (2)

L.B
L.B

Reputation: 116188

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

Upvotes: 1

SidAhmed
SidAhmed

Reputation: 2352

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

Upvotes: 1

Related Questions