Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net DefaultValueAttribute on Properties

Tags:

c#

.net

I got this code in a user control:

[DefaultValue(typeof(Color), "Red")]
public Color MyColor { get; set; }

How can I change MyColor to be its default value?

like image 487
Melursus Avatar asked Apr 01 '09 13:04

Melursus


People also ask

Can we set default value in property c#?

You can assign the default value using the DefaultValueAttribute attribute, as shown below.

How do I set default value in property?

Set a default valueIn the Navigation Pane, right-click the form that you want to change, and then click Design View. 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.

What is attribute default value?

A member's default value is typically its initial value. From this, you may conclude that if you set the DefaultValue attribute for a property, the property is initialized to that value. However, you should set the property's DefaultValue attribute equal to its initialized value.

How do I change the default value for EF core?

In EF core released 27th June 2016 you can use fluent API for setting default value. Go to ApplicationDbContext class, find/create the method name OnModelCreating and add the following fluent API.


1 Answers

The DefaultValueAttribute does not set the property to the value, it is purely informational. The Visual Studio designer will display this value as non-bold and other values as bold (changed), but you'll still have to set the property to the value in the constructor.

The designer will generate code for the property if the value was set by the user, but you can remove that code by right clicking on the property and clicking Reset.

like image 64
OregonGhost Avatar answered Oct 07 '22 20:10

OregonGhost