views:

833

answers:

3

Please consider this example class:

[Serializable]
public class SomeClass
{
    private DateTime _SomeDateTime;

    public DateTime SomeDateTime
    {
     get { return _SomeDateTime; }
     set { _SomeDateTime = value; }
    }
}

I would like to alter the serialization of any DateTime declared in the class according to my own rules. The members of this class will change frequently and I don't want to maintain a custom serializer for every change. Also I would like this behaviour to be inherited by subclasses and not code a custom serializer for every one. The serialization is being output by a web service. Thanks for any help!

+2  A: 

Have you thought about simply using a Nullable date time

public DateTime? SomeDateTime {get; set;}

This way you can actually have a null value as a legitimate value in your class. Typically you want to avoid custom serialization whenever possible. Once you do custom serialization such as implementing ISerializable, then you are stuck with it, and all other derived classes are stuck with it.

Remember what a pain in the butt it is to have to always override the ISerializable members for custom exceptions? This is because System.Exception implements ISerializable and therefore all derived exceptions (that means everything) must implement those members if you ever expect them to cross AppDomains.

Josh
I'm consuming this via a web service so it is automatically converting DateTime? to DateTime.MinValue. I'll correct the question.
Alex Angas
A: 

Well, you can use a "bool ShouldSerializeSomeDateTime()" method to enable/disable serialization of individual members, but I don't think that is quite what you need. Another common option is to add a member that does the format itself:

public string SomeDateTimeFormatted { get { return theField == DateTime.MinValue ? "" : theField.ToString("R");} // or whatever format set { ... opposite ...} }

It is nicer to stick with the inbuilt serialization if you can, though - in part to reduce the amount of code you need to write. Josh's suggestion for a nullable DateTime (DateTime?) is a good one, although it might still not be quite empty-string vs formatted-string - I expect it would use the xsi:nil markup.

Marc Gravell
+1  A: 

look at the OnSerializing and OnDeserializing attributes to call custom methods when your objects are serialized. you can impelment some custom logic in there and decouple the serializing process from the actual datatypes.

Joachim Kerschbaumer
How, exactly, can one do this, if those delegates don't make the SerializationInfo object available?
skolima
well, you dont need a serializationinfo object as you should get a streamingcontext passed to the methods decorated with the OnSerializing attribute. see http://msdn.microsoft.com/en-us/library/system.runtime.serialization.onserializingattribute.aspx for details.
Joachim Kerschbaumer