001
001

Reputation: 65205

Class model - setting default value

When defining the default value, what is the difference between

[DefaultValue("member")]
public string Role { get; set; }

and

public string Role { get; set; } = "member";

Upvotes: 0

Views: 616

Answers (2)

Peter Duniho
Peter Duniho

Reputation: 70701

From the documentation:

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.

In other words, your first example helps tools (like the Windows Forms Designer) to know what the intended default value for a property is. But it does nothing at run-time.

If you want a property to be assigned a default value at run-time, you have to do it yourself, as in the second example you show.

Upvotes: 2

Rob
Rob

Reputation: 27367

The first is an attribute which can be useful for meta-programming. For example, you might want to remember what the default value is if someone clears an input. It has nothing to do with the C# language itself. It does not modify the value of Role.

The second actually sets the property's value to 'member' in memory.

Upvotes: 2

Related Questions