How to get/set a property value of a generic type object

public (return type) myMethod<T>(…)
where T:class
// Create a generic object
Object[] agrs = { (object values / variables of arguements for the constructor) };
T genObj = Activator.CreateInstance(typeof(T), args) as T;

// Get PropertyInfo array for this generic type
System.Reflection.PropertyInfo[] pInfo = genObj.GetType().GetProperties();

// Get the property field you want
var property = pInfo.Where(p => String.Compare(p.Name, “PropertyName”, true) == 0).Single();

// Set the property value
var value = (new property value in its strongly type);
property.SetValue(genObj, value);

// Get the property value
value = (you may need a casting here)property.GetValue(genObj);


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s