You can use an indexer and the reflection API like in the following example
(As other have said you must be very careful)
public class VM_MyClass
{
private static Type ThisType = typeof(VM_MyClass);
public string Name { get; set; }
public DateTime DOB { get; set; }
public object this[string propertyName]
{
get
{
return GetValueUsingReflection(propertyName);
}
set
{
SetValueUsingReflection(propertyName, value);
}
}
private void SetValueUsingReflection(string propertyName, object value)
{
PropertyInfo pinfo = ThisType.GetProperty(propertyName);
pinfo.SetValue(this, value, null);
}
private object GetValueUsingReflection(string propertyName)
{
PropertyInfo pinfo = ThisType.GetProperty(propertyName);
return pinfo.GetValue(this,null);
}
}
You can use it like this:
using System;
using System.Reflection;
namespace Example
{
class Program
{
static void Main(string[] args)
{
VM_MyClass model = new VM_MyClass();
model["Name"] = "My name";
model["DOB"] = DateTime.Today;
Console.WriteLine(model.Name);
Console.WriteLine(model.DOB);
//OR
Console.WriteLine(model["Name"]);
Console.WriteLine(model["DOB"]);
Console.ReadLine();
}
}
}