2

Possible Duplicate:
default value for a static property

I am able to assign default value for a normal default property of a class. But i am not able to assign default value for a static default property of a class like below:-

    public class AppInstance
{
    [DefaultValue(25)]
    public static int AppType { get; set; }
}

When I call AppInstance.AppType, it always return 0 instead of 25. Why? How can i solve it without using a private variable declaration?

Community
  • 1
  • 1
Tamilmaran
  • 1,257
  • 1
  • 10
  • 21

3 Answers3

5

The DefaultValueAttribute only tells the WinForms designer which value is the default value of a property of the form or of a control. If the property has another value, this value will appear bold in the properties window. But it will actually not set the value.

You must assign it a value in the static constructor

static MyClass()
{
    AppType = 25;
}
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
3

You can use a static constructor. It is called automatically to initialize the class before the first instance is created or any static members are referenced.

public class AppInstance
{
    public static int AppType { get; set; }

    static AppInstance()
    {
        AppType = 25;
    }
}
Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
1

I don't see the use for an static member to be created by using get; set; in this scenario. Maybe somebody else can?

So, I would probably just do this:

public class AppInstance
{
    public static int AppType = 25;
}
Davin Tryon
  • 66,517
  • 15
  • 143
  • 132