Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Tagged as

Go to top

Setting a default value for C# Auto-implemented properties

, 12 Jan 2012
Rate this:
Please Sign up or sign in to vote.
After describing it so much, I felt the need to go ahead and implement it. So here goes...using System;using System.Collections.Generic;using System.ComponentModel;using System.Linq.Expressions;using System.Reflection;namespace DefaultValue{ /// /// The...
After describing it so much, I felt the need to go ahead and implement it. So here goes...
 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Reflection;
 
namespace DefaultValue
{
    /// <summary>
    /// The DefaultValueExtensions extends the <see cref="DefaultValueAttribute"/> to allow setting
    /// the initial value of automatic properties generically.
    /// </summary>
    public static class DefaultValueExtensions
    {
        private static Dictionary<Type, Delegate> _dctTypeInitializers = new Dictionary<Type, Delegate>();
 
        /// <summary>
        /// Initializes all of a type's properties by the values defined in the <see cref="DefaultValueAttribute"/>.
        /// </summary>
        /// <typeparam name="T">The type of the object to initialize properties.</typeparam>
        /// <param name="item">The item to initialize properties.</param>
        public static void InitializePropertyDefaults<T>(this T item)
        {
            Type type;
            Delegate d;
            Action<T> action;
 
            type = typeof(T);
 
            lock (DefaultValueExtensions._dctTypeInitializers)
            {
                if (!DefaultValueExtensions._dctTypeInitializers.TryGetValue(type, out d))
                    DefaultValueExtensions._dctTypeInitializers[type] = d = DefaultValueExtensions.CreateTypeInitializer(type);
            }
 
            action = d as Action<T>;
            action(item);
        }
 
        /// <summary>
        /// Creates the lambda expression to initialize the properties on the type with the default values.
        /// </summary>
        /// <param name="type">The type to initialize the properties with the default values.</param>
        /// <returns>A lambda expression to initialize the properties on the type with the default values.</returns>
        private static Delegate CreateTypeInitializer(Type type)
        {
            List<Expression> lstExpressionBody;
            ParameterExpression itemParam;
 
            lstExpressionBody = new List<Expression>();
            itemParam = Expression.Parameter(type, "item");
 
            foreach (var tuple in DefaultValueExtensions.GetPropertiesAndValues(type))
            {
                // Adds the call: item.XXXX = YYYY;
                lstExpressionBody.Add
                (
                    Expression.Assign
                    (
                        Expression.Property(itemParam, tuple.Item1),
                        Expression.Constant(tuple.Item2)
                    )
                );
            }
 
            // Add an empty to the end to ensure that it doesn't return a value.
            lstExpressionBody.Add(Expression.Empty());
 
            return Expression.Lambda(Expression.Block(lstExpressionBody), itemParam).Compile();
        }
        /// <summary>
        /// Iterates over a type's properties to list off all of the properties and the associated default values.
        /// </summary>
        /// <param name="type">The type to examine.</param>
        /// <returns>A list off all of the properties and the associated default values of a type.</returns>
        private static IEnumerable<Tuple<PropertyInfo, object>> GetPropertiesAndValues(Type type)
        {
            object[] defaultValueAttributes;
            DefaultValueAttribute defaultValueAttribute;
 
            foreach (PropertyInfo prop in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                defaultValueAttributes = prop.GetCustomAttributes(typeof(DefaultValueAttribute), true);
 
                if ((defaultValueAttributes != null) && (defaultValueAttributes.Length > 0))
                {
                    defaultValueAttribute = defaultValueAttributes[0] as DefaultValueAttribute;
 
                    yield return new Tuple<PropertyInfo, object>(prop, defaultValueAttribute.Value);
                }
            }
        }
    }
}
 
With its usage as:
 
public MyClass()
{
    this.InitializePropertyDefaults();
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Andrew Rissing
Software Developer (Senior)
United States United States
Since I've begun my profession as a software developer, I've learned one important fact - change is inevitable. Requirements change, code changes, and life changes.
 
So..If you're not moving forward, you're moving backwards.

Comments and Discussions

 
GeneralRe: It isn't about feelings, so much as etiquette in general. I... PinmemberAndrew Rissing12-Jan-12 4:58 
GeneralRe: Andrew, I feel I upset you, sorry. My vote for 1 is not beca... PinmemberMember 308248712-Jan-12 4:35 
GeneralRe: I think "All Time Programming" states it correctly. There a... PinmemberAndrew Rissing12-Jan-12 3:35 
GeneralRe: Strongly speaking in this task I don't see ANY requirements,... PinmemberMember 308248711-Jan-12 20:26 
GeneralReason for my vote of 5 Elegant, performant, not too much co... Pinmemberdojohansen13-Jan-12 3:47 
GeneralReason for my vote of 5 5ed - very elegant and secure code! Pinmemberjohannesnestler12-Jan-12 23:19 
GeneralReason for my vote of 5 Seems to be best of all. I agree wit... PinmemberAll Time Programming11-Jan-12 18:39 
GeneralReason for my vote of 1 Too much code for so simple problem. PinmemberMember 30824879-Jan-12 21:21 
GeneralRe: I would gladly see an alternate of yours that would accompli... PinmemberAndrew Rissing10-Jan-12 3:59 
GeneralRe: Always less code is not important or required. Many times or... PinmemberAll Time Programming11-Jan-12 18:37 
GeneralReason for my vote of 5 Excellent code. PinmemberBillWoodruff9-Jan-12 14:11 
General+5 Fascinating; I wish you would write this up as a CP arti... PinmemberBillWoodruff9-Jan-12 14:10 
GeneralRe: I'll definitely consider it, just need to find the time to d... PinmemberAndrew Rissing9-Jan-12 15:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140921.1 | Last Updated 12 Jan 2012
Article Copyright 2012 by Andrew Rissing
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid