Click here to Skip to main content
15,881,172 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Setting a default value for C# Auto-implemented properties

Rate me:
Please Sign up or sign in to vote.
4.73/5 (8 votes)
12 Jan 2012CPOL 29.3K   2   13
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...

C#
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:

C#
public MyClass()
{
    this.InitializePropertyDefaults();
}

License

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


Written By
Architect
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... Pin
Andrew Rissing12-Jan-12 4:58
Andrew Rissing12-Jan-12 4:58 
GeneralRe: Andrew, I feel I upset you, sorry. My vote for 1 is not beca... Pin
Thornik12-Jan-12 4:35
Thornik12-Jan-12 4:35 
GeneralRe: I think "All Time Programming" states it correctly. There a... Pin
Andrew Rissing12-Jan-12 3:35
Andrew Rissing12-Jan-12 3:35 
GeneralRe: Strongly speaking in this task I don't see ANY requirements,... Pin
Thornik11-Jan-12 20:26
Thornik11-Jan-12 20:26 
GeneralReason for my vote of 5 Elegant, performant, not too much co... Pin
dojohansen13-Jan-12 3:47
dojohansen13-Jan-12 3:47 
GeneralReason for my vote of 5 5ed - very elegant and secure code! Pin
johannesnestler12-Jan-12 23:19
johannesnestler12-Jan-12 23:19 
GeneralReason for my vote of 5 Seems to be best of all. I agree wit... Pin
All Time Programming11-Jan-12 18:39
All Time Programming11-Jan-12 18:39 
GeneralReason for my vote of 1 Too much code for so simple problem. Pin
Thornik9-Jan-12 21:21
Thornik9-Jan-12 21:21 
GeneralRe: I would gladly see an alternate of yours that would accompli... Pin
Andrew Rissing10-Jan-12 3:59
Andrew Rissing10-Jan-12 3:59 
GeneralRe: Always less code is not important or required. Many times or... Pin
All Time Programming11-Jan-12 18:37
All Time Programming11-Jan-12 18:37 
GeneralReason for my vote of 5 Excellent code. Pin
BillWoodruff9-Jan-12 14:11
professionalBillWoodruff9-Jan-12 14:11 
General+5 Fascinating; I wish you would write this up as a CP arti... Pin
BillWoodruff9-Jan-12 14:10
professionalBillWoodruff9-Jan-12 14:10 
GeneralRe: I'll definitely consider it, just need to find the time to d... Pin
Andrew Rissing9-Jan-12 15:01
Andrew Rissing9-Jan-12 15:01 

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

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