• Feeds

    Subscribe in a reader

  • Ads

ContractNamespaceAttribute and Serialization

One of the things that the DataContractSerializer does is create a mapping between CLR type names and XML qnames.

Lots of people know that you can control this mapping on a per-type basis via the [DataContract] attribute, e.g.

namespace Contoso.Serialization
{
  [DataContract( Namespace="http://schemas.contoso.com/2008" )]
  public class Person
  {

     [DataMember]
     public string Name { get; set; }
  }
}

Having to explicitly specify this on every type gets a little laborious, especially if you just want to say "put all types in this CLR namespace into this XML namespace".

Few people know that there's a simple way to do this via the assembly-level ContractNamespaceAttribute:

[assembly: ContractNamespace( "http://schemas.contoso.com/2008", ClrNamespace="Contoso.Serialization" )]

If you have that, then you can just say [DataContract] (sans Namespace="...") and it's just as if you had said [DataContract( Namespace="http://schemas.contoso.com/2008" )] for all [DataContract] types in the Contoso.Serialization namespace.

That comes in handy from time to time and can save some keystrokes.

This has been around since .NET 3.0, but I didn't know about it until recently. Figured not many other people did either :)