Click here to Skip to main content
12,401,737 members (54,165 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

12.6K views
1 bookmarked
Posted

Setting a default value for C# Auto-implemented properties

, 12 Jan 2012 CPOL
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.

You may also be interested in...

Comments and Discussions

 
GeneralRe: It isn't about feelings, so much as etiquette in general. I... Pin
Andrew Rissing12-Jan-12 4:58
memberAndrew Rissing12-Jan-12 4:58 
GeneralRe: Andrew, I feel I upset you, sorry. My vote for 1 is not beca... Pin
Member 308248712-Jan-12 4:35
memberMember 308248712-Jan-12 4:35 
GeneralRe: I think "All Time Programming" states it correctly. There a... Pin
Andrew Rissing12-Jan-12 3:35
memberAndrew Rissing12-Jan-12 3:35 
GeneralRe: Strongly speaking in this task I don't see ANY requirements,... Pin
Member 308248711-Jan-12 20:26
memberMember 308248711-Jan-12 20:26 
GeneralReason for my vote of 5 Elegant, performant, not too much co... Pin
dojohansen13-Jan-12 3:47
memberdojohansen13-Jan-12 3:47 
GeneralReason for my vote of 5 5ed - very elegant and secure code! Pin
johannesnestler12-Jan-12 23:19
memberjohannesnestler12-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
memberAll Time Programming11-Jan-12 18:39 
GeneralReason for my vote of 1 Too much code for so simple problem. Pin
Member 30824879-Jan-12 21:21
memberMember 30824879-Jan-12 21:21 
GeneralRe: I would gladly see an alternate of yours that would accompli... Pin
Andrew Rissing10-Jan-12 3:59
memberAndrew 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
memberAll Time Programming11-Jan-12 18:37 
GeneralReason for my vote of 5 Excellent code. Pin
BillWoodruff9-Jan-12 14:11
memberBillWoodruff9-Jan-12 14:11 
General+5 Fascinating; I wish you would write this up as a CP arti... Pin
BillWoodruff9-Jan-12 14:10
memberBillWoodruff9-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
memberAndrew 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.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160721.1 | Last Updated 12 Jan 2012
Article Copyright 2012 by Andrew Rissing
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid