.NET DefaultValue attribute
The place where I typically used DefaultValue
is for classes which are serialized/deserialized to XML. It does not set the default value during instantiation and doesn't impact autoproperties.
From MSDN:
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.
MSDN - DefaultValueAttribute Class
Edit: As Roland points out, and as others mentioned in their answers the attribute is also used by the Form Designer
C# DefaultValue attribute not working
The Default value attribute only indicates the designer what is the default value of the propery. It does not set it as the actual value of the member behind the property. This is also mentioned on the MSDN page for the default value attribute:
(in the remarks section)
Note
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.
So, as others have already mentioned, you need to set these values in the code yourself (I like to do it in the constructor and not in the declaration of the private members, but I think it's just a matter of personal preference).
How do I declare a DefaultValue attribute whose value is an array of strings?
You could try
[DefaultValue(new string[] { "a", "b" })]
As you want to pass a new string array, you have to instantiate it - that's done by new string[]
. C# allows an initialization list with the initial contents of the array to follow in braces, i.e. { "a", "b" }
.
EDIT: As correctly pointed out by Cory-G, you may want to make sure your actual instances do not receive the very array instance stored in the DefaultValue
attribute. Otherwise, changes to that instance might influence default values across your application.
Instead, you could use your property's setter to copy the assigned array.
DefaultValue attribute is not working with my Auto Property
The DefaultValue attribute is only used to tell the Visual Studio Designers (for example when designing a form) what the default value of a property is. It doesn't set the actual default value of the attribute in code.
More info here: http://support.microsoft.com/kb/311339
.Net DefaultValueAttribute on Properties
It is informal, but you can use it via reflection, for example, place in your constructor the following:
foreach (PropertyInfo p in this.GetType().GetProperties())
{
foreach (Attribute attr in p.GetCustomAttributes(true))
{
if (attr is DefaultValueAttribute)
{
DefaultValueAttribute dv = (DefaultValueAttribute)attr;
p.SetValue(this, dv.Value);
}
}
}
In C#, How to Change the DefaultValue Attribute of a Property in a Class that is Not Inheritable?
Summary: I don't think it is possible to do this via reflection, but here is how I would do it:
First get the property you want:
var defValAttr = typeof (SomeControl.RowCollection)
.GetProperty("yourProperty")
.GetCustomAttributes(typeof(DefaultValueAttribute), false)
.First()
as DefaultValueAttribute;
DefaultValueAttribute has a .Value property, which is readonly. To modify it you need reflection again to change the private .value field:
var valueField= typeof (DefaultValueAttribute)
.GetField("value", BindingFlags.NonPublic
| BindingFlags.GetField
| BindingFlags.Instance);
valueField.SetValue(defValAttr, yourNewDefaultValue);
I have not tested this myself, but as far as I know this will not work. The objects returned by GetCustomAttributes are not the actual attributes; you can get the values of the real attributes this way, but you cannot change them. (see Can attributes be added dynamically in C#?)
However, even if this would work, it would change the DefaultValue for all instances of SomeControl.Rows, whether they are within your custom derived control or in the base control. There is no way to change only the DefaultValue of a single instance, since the this value is stored only once per class, not once per instance. It would be very wasteful if there was a copy of each attribute for each instance of an object.
So in conclusion, I don't think there is a way to do this.
As an alternative, you could decompile the third-party assembly and add your own assembly with InternalsVisibleTo, that way you can access the internal constructor.
Addendum: There may still be a way to do this, depending on what sort of attribute you want to change. The attributes accessible via reflection are as I said probably unchangeable. However The visual studio editor and the whole WPF component model actually uses a TypeDescriptor to manage attributes on top of the basic attribute system built into the language. You may be able to change the attributes used by the TypeProvider, and if code later accesses the attributes via TypeDescriptor, it may see the changed values.
The following is again untested:
var instanceOfRow = instanceOfYourControl.Rows;
var defValAttr = TypeDescriptor
.GetProperties(instanceOfRow)["yourProperty"]
.Attributes[typeof (DefaultValueAttribute)]
as DefaultValueAttribute;
var valueField= typeof (DefaultValueAttribute)
.GetField("value", BindingFlags.NonPublic
| BindingFlags.GetField
| BindingFlags.Instance);
valueField.SetValue(defValAttr, yourNewDefaultValue);
How to assign property value from DefaultValue attribute
Though the intended use of the attribute is not to actually set the values of the properties, you can use reflection to always set them anyway.
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(this))
{
DefaultValueAttribute myAttribute = (DefaultValueAttribute)property.Attributes[typeof(DefaultValueAttribute)];
if (myAttribute != null)
{
property.SetValue(this, myAttribute.Value);
}
}
About usage of DefaultValueAttribute Class in .Net
DefaultValue does NOT set the value.
What it does is tell VisualStudio what the default value is. When a visual element (Button, listbox etc) is selected on a form, and the Property panel is displayed, VS will bold the values of properties which are set to something besides the value given in DefaultValue.
Hence in your case, since AnyValue is false, but it's DefaultValue is true, then is will display false in bold in the Property panel. If you were to manually change it to "true", then it will be displayed non-bolded.
What is the best way to give a C# auto-property an initial value?
In C# 5 and earlier, to give auto implemented properties an initial value, you have to do it in a constructor.
Since C# 6.0, you can specify initial value in-line. The syntax is:
public int X { get; set; } = x; // C# 6 or higher
DefaultValueAttribute
is intended to be used by the VS designer (or any other consumer) to specify a default value, not an initial value. (Even if in designed object, initial value is the default value).
At compile time DefaultValueAttribute
will not impact the generated IL and it will not be read to initialize the property to that value (see DefaultValue attribute is not working with my Auto Property).
Example of attributes that impact the IL are ThreadStaticAttribute
, CallerMemberNameAttribute
, ...
Related Topics
How to Check If an Ip Address Is Within a Particular Subnet
Xmlserialize a Custom Collection with an Attribute
C# Structs: Unassigned Local Variable
Sqlite .Net Performance, How to Speed Up Things
Reading Fromuri and Frombody at the Same Time
Inconsistent Accessibility Error with the Following C# Code. Why
How to Get Current Regional Settings in C#
How to Unescape and Reescape Strings in .Net
How to Create a Generic Class from a String in C#
Passing Parameters to Xslt Stylesheet via .Net
An Integer Array as a Key for Dictionary
In C# Why Can't a Conditional Operator Implicitly Cast to a Nullable Type
How Does Deferred Linq Query Execution Actually Work
Why Would Try/Finally Rather Than a "Using" Statement Help Avoid a Race Condition
How to Log All Thrown Exceptions
There Is No Viewdata Item of Type 'Ienumerable<Selectlistitem>' That Has the Key Country