Click here to Skip to main content
15,395,877 members
Articles / Programming Languages / C#
Alternative
Tip/Trick
Posted 23 Aug 2011

Tagged as

Stats

12K views
2 bookmarked

C# Automatic Property Default Value Extension Methods

Rate me:
Please Sign up or sign in to vote.
4.67/5 (4 votes)
23 Aug 2011CPOL
For .NET 4.0:using System;using System.Collections.Generic;using System.ComponentModel;using System.Reflection;using System.Linq.Expressions;static class AutomaticPropertyExtensions{ private static class Cache where T : class { public static readonly...
For .NET 4.0:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Linq.Expressions;

static class AutomaticPropertyExtensions
{
    private static class Cache<T> where T : class
    {
        public static readonly Action<T> Init;
        public static readonly int PropertyCount;

        static Cache()
        {
            var p = Expression.Parameter(typeof(T), "this");
            var body = Expression.Block(typeof(T)
                .ListPropertiesToReset()
                .Select(pair => Assign(p, pair.Item1, pair.Item2)));

            PropertyCount = body.Expressions.Count;
            if (PropertyCount != 0)
            {
                var result = Expression.Lambda<Action<T>>(body, p);
                Init = result.Compile();
            }
        }
    }
    
    private static Expression Assign(Expression p, PropertyInfo property, object value)
    {
        var prop = Expression.Property(p, property);
        var defaultValue = Expression.Constant(value, property.PropertyType);
        return Expression.Assign(prop, defaultValue);
    }
    
    private static IEnumerable<Tuple<PropertyInfo, object>> ListPropertiesToReset(this Type componentType)
    {
        const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

        return from PropertyInfo property in componentType.GetProperties(flags)
               where property.CanWrite
               let attributes = property.GetCustomAttributes(typeof(DefaultValueAttribute), true)
               where attributes != null && 0 != attributes.Length
               let attribute = (DefaultValueAttribute)attributes[0]
               let defaultValue = attribute.Value
               where defaultValue != null
               select Tuple.Create(property, defaultValue);
    }

    public static int ResetPropsUsingDefaultAttributes<T>(this T instance) where T : class
    {
        if (instance == null) throw new ArgumentNullException("instance");
        if (Cache<T>.Init != null) Cache<T>.Init(instance);
        return Cache<T>.PropertyCount;
    }
}


Usage:
C#
public class TestClass
{
    [DefaultValue(0.3141)]
    public double MyPie { get; set; }

    [DefaultValue("Pizza")]
    public string MyLove { get; set; }

    public TestClass()
    {
        this.Reset();
    }

    public void Reset()
    {
        this.ResetPropsUsingDefaultAttributes();
    }

    public override string ToString()
    {
        return string.Format("MyPie = {0}, MyLove = {1}",
            MyPie, MyLove == null ? "null" : MyLove);
    }
}

License

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

Share

About the Author

Richard Deeming
Software Developer CodeProject
United Kingdom United Kingdom
I started writing code when I was 8, with my trusty ZX Spectrum and a subscription to "Input" magazine. Spent many a happy hour in the school's computer labs with the BBC Micros and our two DOS PCs.

After a brief detour into the world of Maths, I found my way back into programming during my degree via free copies of Delphi and Visual C++ given away with computing magazines.

I went straight from my degree into my first programming job, at Trinet Ltd. Eleven years later, the company merged to become ArcomIT. Three years after that, our project manager left to set up Nevalee Business Solutions, and took me with him. Since then, we've taken on four more members of staff, and more work than you can shake a stick at. Smile | :)

Between writing custom code to integrate with Visma Business, developing web portals to streamline operations for a large multi-national customer, and maintaining RedAtlas, our general aviation airport management system, there's certainly never a dull day in the office!

Outside of work, I enjoy real ale and decent books, and when I get the chance I "tinkle the ivories" on my Technics organ.

Comments and Discussions

 
GeneralReason for my vote of 5 Quite an improvement. Doesn't look a... Pin
Itai Basel23-Aug-11 12:29
MemberItai Basel23-Aug-11 12:29 

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.