Setting List Properties using Reflection

I’m working on a feature which allows you make configuration changes to List instances on feature activation. The exact configuration is provided to the feature via feature properties and I wanted to be able to set property values on the SPList instance dynamically using reflection.

Here’s the code which does that;

private static bool SetListProperty(SPList list, string propertyName, string propertyValue)
	if (list == null) 
		throw new ArgumentNullException("list");
	if (string.IsNullOrEmpty(propertyName)) 
		throw new ArgumentNullException("propertyName");

	var t = list.GetType();
	if (t == null) throw new Exception("Invalid reflection object");
	var pi = t.GetProperty(propertyName);
	if (pi == null) throw new Exception("Invalid property: " + propertyName);

	if (!pi.CanWrite)
		throw new NotSupportedException("Property " + propertyName + " is Read Only!");

		var ovalue = Convert.ChangeType(propertyValue, pi.PropertyType);
		pi.SetValue(list, ovalue, null);
	catch(Exception ex)
		throw new Exception(string.Format("Unable to set property: {0} to: {1}", 
										propertyName, propertyValue), ex);	

	return true;

Published by

Phil Harding

SharePoint Consultant, Developer, Father, Husband and Climber.

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 )

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.