Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make default value with a struct property?

Tags:

c#

struct

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.

like image 605
Mark Attwood Avatar asked Dec 31 '10 21:12

Mark Attwood


2 Answers

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

like image 120
Hans Passant Avatar answered Oct 06 '22 00:10

Hans Passant


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

like image 26
decyclone Avatar answered Oct 06 '22 00:10

decyclone