How do you give a C# Auto-Property a default value?Ask Questions

 Posted on 17 days ago

How do you give a C# Auto-Property a default value? I either use the constructor, or revert to the old syntax.

Using the Constructor:

class Person

{

    public Person()

   {

          Name = "Default Name";

   }

   public string Name { get; set; }

}

Using normal property syntax (with a default value)

private string name = "Default Name";

public string Name { get { return name; } set { name = value; } }

 

Is there a better way?

Share On: facebook gplus twitter
profile
Asked by Chirag Bhatt on 17 days ago Score: 18 points
Add Comment:

Comments

1 Answers

0 Corrected Answers
Aproved Answers
0
Profile
Answered by Helder Sepulveda on 10/4/2019 8:06:06 AM Score: 42 points

In C# 5 and earlier, to give auto implemented properties a default value, you have to do it in a constructor.

The ability to have auto property initializers is included since C# 6.0. The syntax is:

public int X { get; set; } = x; // C# 6 or higher

DefaultValueAttribute ONLY work in the vs designer. It will not initialize the property to that value.

See DefaultValue attribute is not working with my Auto Property

Comments

Add Comment:

Post Your Answers

Existing Members

Sign in to your account
Email Address
Password
New Member?
Sign up and complete profile
Full Name
Email Address
I have read and agree to the Terms of Service and Privacy Policy
Please subscribe me to the StoodQ newsletters
Guideline to answer a question:

Useful tips to submit your answer
Please read below guidelines before you submit your answer for question.

  • Read and understand question for which you are submitting your answer.
  • Try to avoid grammatical and spell mistake while answering.
  • Do not post any irrelevant information in your answer.
  • Explain your answer with example or any reference link to help who posted question.
  • If you find irrelevant question, please report it to support. Click here to contact support.
  • You agree to the privacy policy and terms of use to submit any contents.

Note: StoodQ is online developers community which helps developer for their difficulty, lets help them with your value contribution.