Assign value from DefaultValueAttribute

There exists DefaultValueAttirbute class that allows declare initial value for property. But, as it is stated in MSDN:

A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute’s value. You must set the initial value in your code.

Briefly, there is code snippet that assign default value to property:

/// <summary>
/// Set value to the property from DefaultValue attribute
/// or do nothing if the attribute is not defined.
/// </summary>
/// <param name="thisObject">Object that is investigated.</param>
/// <param name="propertyName">Property name, could be omitted.</param>
/// <returns>TRUE if property value is set.</returns>
public static bool SetDefaultValue<T>(
			this object thisObject,
			[CallerMemberName]string propertyName = null)
	if (thisObject == null || string.IsNullOrEmpty(propertyName))
		return false;

	var propertyCollection = TypeDescriptor.GetProperties(thisObject);
	var property = propertyCollection[propertyName];
	var attribute = (DefaultValueAttribute)property?.Attributes[typeof(DefaultValueAttribute)];
	if (attribute == null)
		return false;

	// attribute.Value could has correct value 'null'
	var newValue = attribute.Value == null ? default(T) : Convert.ChangeType(attribute.Value, typeof(T));
	if (!property.IsReadOnly)
		property.SetValue(thisObject, newValue);
		var propertyInfo = thisObject.GetType().
				GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
		if (propertyInfo == null)
			return false;
		propertyInfo.SetValue(thisObject, newValue);
	return true;

Example of the usage:

/// <summary>
/// Method initiates an object by default values.
/// </summary>
public void Init()

Listed code covers the following issues:

  • Property could not have DefaultValue attribute. In this case, method returns false;
  • TypeDescriptor class is much faster than the using Type.GetProperty() method, so at first method uses the faster approach;
  • DefaultValue attribute could defined null as value, and it would be correctly assigned;
  • Property could be internal or protected internal. In this case TypeDescriptor silently do nothing and method uses reflection methods.

Various methods like SetDefaultValue and GetDefaultValue are included to NuGet package Ikc5.TypeLibrary, version Current version of code is accessible on GitHub Blog repository.

1. All used IP-addresses, names of servers, workstations, domains, are fictional and are used exclusively as a demonstration only.
2. Information is provided «AS IS».

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 )

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.