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

Tagged as

C# Automatic Property Default Value Extension Methods

, 23 Aug 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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:
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)
                .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;
public class TestClass
    public double MyPie { get; set; }
    public string MyLove { get; set; }
    public TestClass()
    public void Reset()
    public override string ToString()
        return string.Format("MyPie = {0}, MyLove = {1}",
            MyPie, MyLove == null ? "null" : MyLove);


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


About the Author

Richard Deeming
Software Developer Nevalee Business Solutions
United Kingdom United Kingdom
No Biography provided
Follow on   Twitter   Google+

Comments and Discussions

GeneralReason for my vote of 5 Quite an improvement. Doesn't look a... PinmemberItai Basel23-Aug-11 13:29 
Reason for my vote of 5
Quite an improvement. Doesn't look as hammered Smile | :)
I do think that caching might not be necessary in my case since I don't really reset anywhere other then the constructor and only have one or two instances of the class I needed this for - but it's great for classes who need multiple resets or instances.
Also - it's quite a nice continuation of the C# exercise... And a nice future reference for me since I've just recently moved from C (or rather added C# to my C since I still have preference for C in many situations).
Thanks again - cheers;

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 | Terms of Use | Mobile
Web04 | 2.8.150327.1 | Last Updated 23 Aug 2011
Article Copyright 2011 by Richard Deeming
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid