Skip to Content
Programming WCF Services
book

Programming WCF Services

by Juval Lowy
February 2007
Intermediate to advanced
634 pages
16h 1m
English
O'Reilly Media, Inc.
Content preview from Programming WCF Services

Delegates and Data Contracts

All delegate definitions are compiled into serializable classes, and so in theory your data contract types could contain delegates as member variables:

[DataContract]
class MyDataContract
{
   [DataMember]
   public EventHandler MyEvent;
}

or even as events (note the use of the field qualifier):

[DataContract]
class MyDataContract
{
   [field:DataMember]
   public event EventHandler MyEvent;
}

In practice, the imported data contract contains an invalid delegate definition when it refers to a custom delegate. While you could manually fix that definition, the bigger problem is that when you serialize an object that has a delegate member variable, the internal invocation list of the delegates is serialized too. In most cases, this is not the desired effect with services and clients, because the exact structure of the list is local to the client or the service, and should not be shared across the service boundary. In addition, there are no guaranties that the target objects in the internal list are serializable or are valid data contracts. Consequently, sometimes the serialization will work, and sometimes it will fail.

The simplest way to avoid this pitfall is not to apply the DataMember attribute on delegates. If the data contract is a serializable type, you need to explicitly exclude the delegate from the data contract:

[Serializable]
public class MyClass
{
   [NonSerialized]
   EventHandler m_MyEvent;
}
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming WCF Services, 2nd Edition

Programming WCF Services, 2nd Edition

Juval Lowy
Pro WCF: Practical Microsoft SOA Implementation

Pro WCF: Practical Microsoft SOA Implementation

Chris Peiris, Dennis Mulder, Shawn Cicoria, Amit Bahree, Nishith Pathak
Mastering ASP.NET Web API

Mastering ASP.NET Web API

Mithun Pattankar, Malendra Hurbuns

Publisher Resources

ISBN: 0596526997Supplemental ContentErrata Page