Click here to Skip to main content
15,565,801 members
Articles / Programming Languages / C#
Alternative
Tip/Trick
Posted 5 Jan 2012

Tagged as

Stats

26K views
2 bookmarked

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