How to get and set properties of an object dynamically with reflection

These two methods can be used on on object so that you can e.g. parse an XML file that has changes in it, and make changes on an object based on the strings in the XML file.

saveSetProperties

using System;
using System.Reflection;

namespace TestSetPropertyValue834
{
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer { Id = 1, FirstName = “Jim”, LastName = “Smith” };

Console.WriteLine(customer.LastName);
Console.WriteLine(customer.GetPropertyValueAsString(“LastName”));
customer.SetPropertyValueWithString(“LastName”, “SmithChanged”);
Console.WriteLine(customer.GetPropertyValueAsString(“LastName”));
Console.ReadLine();
}
}

class Customer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }

public string GetPropertyValueAsString(string propertyName)
{
PropertyInfo prop = typeof(Customer).GetProperty(propertyName);
object value = prop.GetValue(this, null);
return value.ToString();
}

public void SetPropertyValueWithString(string propertyName, string value)
{
PropertyInfo prop = typeof(Customer).GetProperty(propertyName);
prop.SetValue(this, value, null);
}
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: