0

I have created a property like below and the default value specified is not working.

[DefaultValue(100)]
public int MyProperty
{
   get;
   set;
}

but the property doesn't returns the specified default value, instead it returns 'O'

Could anyone please clarify me?

Regards,

Amal
  • 576
  • 1
  • 6
  • 26
  • Follow this link: http://stackoverflow.com/questions/40730/how-do-you-give-a-c-sharp-auto-property-a-default-value – Kingsman Apr 25 '17 at 09:33

2 Answers2

2

If you're using c# 6.0 you can use this to set default property value:

public int MyProperty { get; set; } = 100;
barzozwierz
  • 148
  • 2
  • 9
1

You're using a DefaultValue attribute.

A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.

https://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute(v=vs.110).aspx

In C# 5 an below, to give properties a default value, you have to do it in the constructor.

public class MyClass
{
    public MyClass() {
        MyProperty = 100;
    }

    public int MyProperty {get; set;}
}

In version 6 (and above) of C# you can do:

public int MyProperty { get; set; } = 100;
Alex
  • 37,502
  • 51
  • 204
  • 332