Mark Attwood
Mark Attwood

Reputation: 4412

How to make default value with a struct property?

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.

Upvotes: 6

Views: 12617

Answers (3)

Hans Passant
Hans Passant

Reputation: 942468

[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.

Upvotes: 12

decyclone
decyclone

Reputation: 30840

[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

Remarks:

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.

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.

Upvotes: 6

cdhowie
cdhowie

Reputation: 169478

This depends on the property type -- you can only use constant values in attributes, so it would have to be a primitive type, a string, an enum type, or any other type that is valid in const context.

So if your property is a string, you would just do something like:

[DefaultValue("foo")]
public string SomeProperty { get; private set; }

Note that this will not affect the behavior of the struct's default constructor, which will still initialize SomeProperty to null; this attribute only affects the behavior of Visual Studio's property pane.

Upvotes: 1

Related Questions