I would like to know how to apply [DefaultValue] attribute to a struct property. You can notice that Microsoft does it with Form's Size and many other properties. Their values' types are Size, Point, etc. I would want to do the same thing with my custom struct.
[DefaultValue(typeof(Point), "0, 0")]
Would be an example. Using a string to initialize the value is a necessary evil, the kind of types you can use in an attribute constructor are very limited. Only the simple value types, string, Type and a one-dimensional array of them.
To make this work, you have to write a TypeConverter for your struct:
[TypeConverter(typeof(PointConverter))]
[// etc..]
public struct Point
{
// etc...
}
Documentation on type converters in the MSDN library isn't great. Using the .NET type converters whose source you can look at with the Reference Source or reverse-engineer with Reflector is a great starting point to get your own working. Watch out for culture btw.
[DefaultValue]
attribute is for designer/code generator/etc only. You cannot use it for structs
. structs
out of all are value types and can don't support default constructor. When object of a struct
is created, all of it's properties/fields are set to their default values. You cannot change this behavior.
MSDN reference:
http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx
You can create a DefaultValueAttribute with any value. A member's default value is typically its initial value. A visual designer can use the default value to reset the member's value. Code generators can use the default values also to determine whether code should be generated for the member.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With