DefaultValue for Enum not working.

17. February 2012 18:13 by Mrojas in VB6 Migration  //  Tags: , , , , ,   //   Comments (0)

Today I was writting a custom control which had a custom property whose type was an EnumType.

I needed the DefaultVAlue attribute so Visual Studio.NET will not serialize the value to the container's code.

Usually in C# you can do something like:

[DefaultValue(TheEnum.TheValue)]
public TheEnum MyProperty
{
get { ... }
set { ... }
}
And that works. Well it does not work in VB.NET
To use an enum value for an Enumeration type in VB.NET you should write something like:
<DefaultValue(GetType(TheEnum), "TheValue")> _
Property MyProperty as TheEnum
   Get
       ...
   End Get
   Set 
        ...
   End Set
End Property
 

Control Property Serialization in .NET

While solving a bug with a custom class that extended the System.Data.DataSet class, I found a situation where the class implemented, the ISerializable interface, but for some reason, during the call to the base.GetObjectData in my serialization code it was trying to get the value of some properties that caused an exception.

The reason was that those properties were not “ready” because my serialization code had not finish initializing the object. But why was the Dataset.GetObjectData trying to get or set those values.

It seems that there is some code in the dataset that used reflection to get the object properties and try to serialize them. I did not want that.
How could I stop the framework from doing that?


I thought of the NonSerializable attribute but that works only on fields and what I have is a property.

I thought of the XmlIgnore attribute but it had no effect.

Why!!!!

Well I finally found that you can add a couple of (not attributes) methods to your component.

They should be named Reset<Property>() and ShouldSerialize<Property>() and returning a boolean value
from these functions will control if the properties are serialized or not.

For more info see MSDN page for ShouldSerialize