0
class Program
{
    class B
    {
        [DefaultValue(2)]
        public int x, y;

        [DefaultValue(5)]
        public int z;
    }

    static void Main(string[] args)
    {
        B b = new B();
        Console.WriteLine(String.Format("{0} {1} {2}", b.x, b.y, b.z));
    }
}

Result: 0, 0, 0

This DefaultValueAttribute doesn't work in console application, or i made something wrong?

Edit:

Somebody said about properties with get,set, but this doesn't work too:

class Program
{
    public class A
    {
        [DefaultValue("123")]
        public string Name { get; set; }
    }

    static void Main(string[] args)
    {
        var a = new A();
        Console.WriteLine(a.Name);
    }
}

Result: empty string

Maxim Zhukov
  • 10,060
  • 5
  • 44
  • 88

4 Answers4

3

DefaultValue doesn't really do anything, it has indicative function so that other code can look for it, MSDN explains:

A visual designer can use the default value to reset the member's value. Code generators can use the default values also to determine whether code should be generated for the member. 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.

Andrey
  • 59,039
  • 12
  • 119
  • 163
2

Please see: DefaultValueAttribute Class

Specifies the default value for a property.

x, y and z are no properties, but fields. Try this:

    class B
    {
        public int x, y, z;
        public B()
        {
            x = y = 2;
            z = 5;
        }
    }
ProgramFOX
  • 6,131
  • 11
  • 45
  • 51
  • I updated my question with property `Name {get; set;}`. Is it a property? If it isn't, show me please example, i can't understand that – Maxim Zhukov Aug 02 '13 at 09:08
  • @FSou1: Yes, that's a property. But as you can read in the answer of Andrey, `DefaultValue` doesn't really do anything. – ProgramFOX Aug 02 '13 at 09:11
2

DefaultValue as an attribute is used by certain classes to do something with your object at runtime (e.g. a serializer could decide not to serialize z if its value is 5, as that is the default).

The attribute is not used by the compiler to generate a default constructor for your class.

You should instead define a default constructor as follows:

class B {
    public B() { 
        x = y = 2;
        z = 5;
    }
}
Paolo Tedesco
  • 55,237
  • 33
  • 144
  • 193
1

You are expect too much from the .net attribute. Attributes are just the extension of meta data. That is to say, the compiler just bind this sorta information to the specific property, not setting the real value you are expecting. So if you wanna get the value set, there must be some extra code either written by yourself or the other framework did for you. You may check this link on stack overflow. .Net DefaultValueAttribute on Properties

Community
  • 1
  • 1
Ethan Wang
  • 98
  • 1
  • 7