Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default value for Auto-Implemented Properties in ASP.NET [duplicate]

I came to know that C# 3.0 comes with a new feature of Auto-Implemented Properties,I liked it as we don't have to declare extra private varible in this (compare to earlier property), earlier I was using a Property i.e.

private bool isPopup = true; public bool IsPopup {     get     {       return isPopup;     }     set     {       isPopup = value;     } } 

Now I've converted it into Auto-Implemented property i.e.

public bool IsPopup {     get; set; } 

I want to set the default value of this property to true without using it not even in page_init method, I tried but not succeeded, Can anyone explain how to do this?

like image 557
Imran Rizvi Avatar asked Nov 28 '11 09:11

Imran Rizvi


People also ask

How do you change default property value?

Right-click the control that you want to change, and then click Properties or press F4. Click the All tab in the property sheet, locate the Default Value property, and then enter your default value. Press CTRL+S to save your changes.

Can we set default values for model?

In practice, you could create the ViewModel, and override these defaults with values pulled from a database entry (using the data-backed model), but as-is, this will always use these default values.

What is the point of auto-implemented properties in C#?

Auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects.

What is the use of default value in the properties?

The DefaultValue property specifies text or an expression that's automatically entered in a control or field when a new record is created. For example, if you set the DefaultValue property for a text box control to =Now(), the control displays the current date and time.


1 Answers

You can initialize the property in the default constructor:

public MyClass() {    IsPopup = true; } 

With C# 6.0 it is possible to initialize the property at the declaration like normal member fields:

public bool IsPopup { get; set; } = true;  // property initializer 

It is now even possible to create a real read-only automatic property which you can either initialize directly or in the constructor, but not set in other methods of the class.

public bool IsPopup { get; } = true;  // read-only property with initializer 
like image 134
slfan Avatar answered Oct 11 '22 14:10

slfan