Search code examples
c#.netwcfserializationdatacontract

Is it correct to serialize an event? (Applying a DataMember attribute)


A very simple question...

Is it correct to apply a DataMember attribute to an event or a delegate to let it be serialized?

Consider what I'm thinking about this:

1) Well, a delegate is a type, based on other types, so as long as those types are serializable themselves there is no need (not correct) to serialize a delegate.

2) Given that an event is based on a delegate, and that a delegate (because of what said in 1) does not need direct serialization, I assume an event does not need to be marked as serializable.

So, my question is:

Is it correct applying serialization attributes to events and delagates?

If the answer is "NO! No need to make them serializable", Are 1) and 2) correct?

Another question: What elements in a class a developer needs to mark as serializable (using DataMember on them)?

Thankyou


Solution

  • No it is not correct. DataMember can be applied only on property or field - that is defined by AttributeTargets:

    [AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field, 
        Inherited = false, AllowMultiple = false)]
    public sealed class DataMemberAttribute : Attribute
    { ... }
    

    AttributeTargets have separate value for Enum and Delegate.

    Serialization delegate or event in distributed system doesn't make sense. You are passing data in interoperable format. Message can contain only data. There is nothing to describe delegates (object oriented pointer to the method living in your process memory) or events (trigger for delegates living in your process memory).

    If you want to have data contract's events on your client you must share the assembly with the contract between the service and the client. In such case both sides will have the same type (with all events, methods, readonly properties, etc.) and they will transfer only data stored in an instance of the type.