views:

64

answers:

2

Hi, I need to set a default value for a property, but I can't do it like this:

private int prop = 1;

public Prop { get {return prop;}... }

Because I need to serialize this class, and if I do it, I loose the default value. Exists any solution that works after the serialization and before, adding an attribute to the property or something like this?

I'm working with c# with framework 3.5. Thanks.

A: 

DefaultValueAttribute

[DefaultValue("SomeValue")]
public string Prop { get; set; }

You can read a lot about serialization here: http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx

Jesper Palm
the DefaultValue Attribute is to tell to the property pages that is the default value expected for a property, maybe my question is wrong, I need to set the "Initial value" and persist this value after the serialization.In your sample code, If I ask for the value of Prop I get string.Empty, not "SomeValue".
Ariel Larraburu
I misunderstood your question. Take a look a the OnSerializingAttribute instead.
Jesper Palm
Yes, I think I need to use the OnSerializationAttribute, thanks
Ariel Larraburu
A: 

There is also:

    ''' <summary>
    ''' The defaults size for the list item.
    ''' </summary>
''' <value>Size.</value>
''' <returns>Size.</returns>
''' <remarks></remarks>
<Category("Appearance")> _
<Description("The defaults size for the list item.")> _
  Public Property DefaultItemSize() As Size Implements IVisualList.DefaultItemSize
    Get
        Return m_DefaultItemSize
    End Get
    Set(ByVal value As Size)
        m_DefaultItemSize = value
    End Set
End Property

Protected Overridable Function ShouldSerializeDefaultItemSize() As Boolean
    If m_DefaultItemSize.Equals(New Size(100, m_CellHeight)) Then Return False
    Return True
End Function

or

Another option may be to use these attributes:

[OnSerializing()]

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.onserializingattribute.aspx

[OnDeserializing()]

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.ondeserializingattribute.aspx

eschneider
I can't use custom serializators. The idea is to make an Entity class that includes information about constraints and other things. For example. I need to create an entity class named "Person", with a "name" property. And on an other property (for example name_MaxLength" and I want to specify the max length for the "name" property and use this property into the UI, bussines rules, validators, dinamic creation of store procedures... But, when I use this entity with webservices I loose the initial value, because I only have the scheema of the entity class, I don't have the implementation.
Ariel Larraburu