Getting a Data Contract Name and Namespace From a Type July, 2009
I just had a requirement in the project I'm working on to get a data contract name and namespace from a type and found that there really isn't an easy, built in way to do it (Without actually serializing an instance of the type). After looking around with reflector I found the methods that the DataContractSerializer uses but found it was a little too complex and dangerous to try to strip the code from the framework or write my own (Especially when it comes to formulating generic type names). So I found a simple alterative which I don't really like but it works. Basically you instantiate the type in question and run it through the serializer and grab the root element name and namespace:
public class DataContractTypeInfo { public DataContractTypeInfo() { Name = string.Empty; TypeNamespace = string.Empty; } private DataContractTypeInfo(string name, string typeNamespace) { Name = name; TypeNamespace = typeNamespace; } public string Name { get; private set; } public string TypeNamespace { get; private set; } public static DataContractTypeInfo Generate(Type type) { if (type.FullName.StartsWith("System.")) return new DataContractTypeInfo(); if (type.ContainsGenericParameters) return new DataContractTypeInfo(); DataContractSerializer serializer = new DataContractSerializer(type); MemoryStream objectStream = new MemoryStream(); object instance = null; if (type.IsArray) Activator.CreateInstance(type, new object[] {0}); else Activator.CreateInstance(type); serializer.WriteObject(objectStream, instance); objectStream.Position = 0; XDocument objectDocument = XDocument.Load(new XmlTextReader(objectStream)); return new DataContractTypeInfo(objectDocument.Root.Name.LocalName, objectDocument.Root.Name.NamespaceName); } }
This code took about 20 ms to get the info of a type that had about 5 members.