How to make default value using struct property?

I would like to know how to apply the [DefaultValue] attribute to a struct property. You may notice that Microsoft does this using a form and many other properties. Their values ​​are Size, Point, etc. I would like to do the same with my custom structure.

+4
source share
3 answers
[DefaultValue(typeof(Point), "0, 0")] 

It is an example. Using a string to initialize a value is a necessary evil; the types of types that you can use in the attribute constructor are very limited. Only simple value types, string, type and one-dimensional array of them.

To do this, you need to write a TypeConverter for your structure:

 [TypeConverter(typeof(PointConverter))] [// etc..] public struct Point { // etc... } 

The documentation for type converters in the MSDN library is small. Using .NET converters, the source of which you can see using the Reference Source or reverse engineer with Reflector, is a great starting point for getting your own work. Follow the culture By the way.

+9
source

[DefaultValue] attribute is only for code generator / generator, etc. You cannot use it for structs . structs from all types of values ​​and cannot support the default constructor. When an a struct object is created, all its properties / fields are set to default values. You cannot change this behavior.

MSDN Link:

http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx

Note:

You can create a DefaultValueAttribute attribute with any value. Default Member The value is usually its initial value. The visual designer can use the reset value of the member value. Code generators can use values ​​that also determine whether code should be generated for a member.

Note:

A DefaultValueAttribute does not call a member automatically initialized by the cost attribute. You must set the initial value in your code.

+5
source

It depends on the type of property β€” you can only use constant values ​​in attributes, so it must be a primitive type, string, enumeration type, or any other type that is valid in the context of const .

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 default constructor, which initializes SomeProperty to null anyway; this attribute only affects the behavior of the Visual Studio property panel.

+1
source

Source: https://habr.com/ru/post/1333915/


All Articles