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

Tagged as

Setting a default value for C# Auto-implemented properties

, 7 Jan 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
While leaving aside the performance penalties, it is a reasonable approach to make code cleaner.Though you can further benefit from the extension methods:public static void InitDefaults(this object o){ PropertyInfo[] props = o.GetType().GetProperties(BindingFlags.Public |...
While leaving aside the performance penalties, it is a reasonable approach to make code cleaner.
 
Though you can further benefit from the extension methods:
 
public static void InitDefaults(this object o)
{
    PropertyInfo[] props = o.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
 
    foreach (PropertyInfo prop in props)
    {
        if (prop.GetCustomAttributes(true).Length > 0)
        {
            object[] defaultValueAttribute =
                prop.GetCustomAttributes(typeof(DefaultValueAttribute), true);
 
            if (defaultValueAttribute != null)
            {
                DefaultValueAttribute dva = defaultValueAttribute[0] as DefaultValueAttribute;
 
                if (dva != null)
                    prop.SetValue(o, dva.Value, null);
            }
        }
    }
}
 
public MyClass()
{
    this.InitDefaults();
} 
 
Taken from:
Setting Default Values on Automatic Properties[^]

License

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

Share

About the Author

Oleg Shilo
Technical Lead
Australia Australia
I was born in Ukraine. After completing the university degree worked there as a Research Chemist. Last 18 years I live in Australia where I've got my second qualification as a Software Engineer.
 
"I am the lucky one: I do enjoy what I am doing!"

Comments and Discussions

 
GeneralI would recommend not including the BindingFlags.Static flag... PinmemberMember 84130209-Jan-12 23:33 
GeneralReason for my vote of 5 Most simplest and useful solution. PinmemberMember 30824879-Jan-12 22:20 
GeneralReason for my vote of 5 My 5: avoiding redundant code! PinmemberAndreas Gieriet6-Jan-12 13:20 

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
Web03 | 2.8.141223.1 | Last Updated 7 Jan 2012
Article Copyright 2012 by Oleg Shilo
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid