Say I have a class B defined as follows:
public class B
{
public int Id { get; set; }
}
Then you could get the value of the id like this:
var b = new B();
b.Id = 60;
int id = GetId(b);
with the GetId
method defined as follows:
public static int GetId(object o)
{
var idProperty = o.GetType().GetProperties().FirstOrDefault(p => p.Name == "Id");
if (idProperty == null)
throw new ArgumentException("object does not have an Id property", "o");
if (idProperty.PropertyType.FullName != typeof(Int32).FullName)
throw new ArgumentException("object has an Id property, but it is not of type Int32", "o");
return (int)idProperty.GetValue(o, new object[] { });
}
A more generic solution would be to make a method like this:
public static T GetProperty<T>(object o, string propertyName)
{
var theProperty = o.GetType().GetProperties().FirstOrDefault(p => p.Name == propertyName);
if (theProperty == null)
throw new ArgumentException("object does not have an " + propertyName + " property", "o");
if (theProperty.PropertyType.FullName != typeof(T).FullName)
throw new ArgumentException("object has an Id property, but it is not of type " + typeof(T).FullName, "o");
return (T)theProperty.GetValue(o, new object[] { });
}
which would be called like so:
var b = new B();
b.Id = 60;
int id = GetProperty<int>(b, "Id");