Set default value for Properties - Web Dev And Stuff
Thursday, September 18, 2008 12:25 PM djsolid

Set default value for Properties

Many times I needed to set a default value for a property.

For example at the property below

public string Property1 {get; set;}

I wanted a default value "Value1". The only way was to create a private field or to set it in code like Property1 = "Value1" somewhere.

What if I wanted to do this for all my properties ?

For this case i decided to create a custom attribute which does that thing. Takes a value and if the value of the current property is null sets it to the given value.


To be more specific let's begin with the custom attribute class:

 [global::System.AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
sealed class DefaultValueAttribute : Attribute
readonly object defaultValue;
readonly Type valueType;

public DefaultValueAttribute(object defaultValue, Type valueType)
this.valueType = valueType;
this.defaultValue = Convert.ChangeType(defaultValue, valueType);
public Type ValueType { get { return valueType; } }
public object DefaultValue
get { return defaultValue; }

Then we have a helper class with an extension method :

public static class DefaultValueAttributeHelper
public static void SetDefaultValues(this object obj)
Type t = obj.GetType();
foreach (var item in t.GetProperties())
foreach (var attr in item.GetCustomAttributes(typeof(DefaultValueAttribute), true))
DefaultValueAttribute val = ((DefaultValueAttribute)attr);
if (item.GetValue(obj, null) == null ||
((item.GetValue(obj, null).ToString() == "0") &&
(val.ValueType != typeof(string))))
item.SetValue(obj, val.DefaultValue, null);


And finally how this can be used  for example at an ASP.NET Page:


public partial class UserDetails : System.Web.UI.Page
public UserDetails()
protected void Page_Load(object sender, EventArgs e)
Response.Write(StringProp + "<br>" + IntProp + "<br>" + (DoubleProp + 1));

[DefaultValueAttribute("6.11354", typeof(double))]
public double DoubleProp { get; set; }

[DefaultValueAttribute("6", typeof(int))]
public int IntProp { get; set; }

[DefaultValueAttribute("String1", typeof(string))]
public string StringProp { get; set; }


Well that's all ... This is really simple. Next step is to create an interface so the above attirbute can be used with custom objects.

If anyone has any improvements please let me know!

kick it on

Filed under: , , , , ,


No Comments