Click here to Skip to main content
15,885,216 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Setting a default value for C# Auto-implemented properties

Rate me:
Please Sign up or sign in to vote.
5.00/5 (5 votes)
7 Jan 2012CPOL 17K   3
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:

C#
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)


Written By
Program Manager
Australia Australia
I was born in Ukraine. After completing the university degree worked there as a Research Chemist. Last 23 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... Pin
Chris Ross 29-Jan-12 22:33
Chris Ross 29-Jan-12 22:33 
GeneralReason for my vote of 5 Most simplest and useful solution. Pin
Thornik9-Jan-12 21:20
Thornik9-Jan-12 21:20 
GeneralReason for my vote of 5 My 5: avoiding redundant code! Pin
Andreas Gieriet6-Jan-12 12:20
professionalAndreas Gieriet6-Jan-12 12:20 

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.