Merge pull request #1668 from alexanderkyte/bug1856
[mono.git] / mcs / class / System.Runtime.Serialization / ReferenceSources / XmlDataContract_static.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Reflection;
5 using System.Xml;
6 using System.Xml.Serialization;
7
8 namespace System.Runtime.Serialization
9 {
10         internal partial class XmlDataContract
11         {
12         internal CreateXmlSerializableDelegate GenerateCreateXmlSerializableDelegate()
13         {
14                                 return () => new XmlDataContractInterpreter (this).CreateXmlSerializable ();
15                 }
16         }
17         
18         internal class XmlDataContractInterpreter
19         {
20                 XmlDataContract contract;
21                 
22                 public XmlDataContractInterpreter (XmlDataContract contract)
23                 {
24                         this.contract = contract;
25                 }
26                 
27                 public IXmlSerializable CreateXmlSerializable ()
28                 {
29                         Type type = contract.UnderlyingType;
30                         object value = null;
31                         if (type.IsValueType)
32                                 value = FormatterServices.GetUninitializedObject (type);
33                         else
34                                 value = GetConstructor ().Invoke (new object [0]);
35                         return (IXmlSerializable) value;
36                 }
37
38                 ConstructorInfo GetConstructor ()
39                 {
40                         Type type = contract.UnderlyingType;
41
42                         if (type.IsValueType)
43                                 return null;
44
45                         ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, Globals.EmptyTypeArray, null);
46                         if (ctor == null)
47                                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.IXmlSerializableMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type))));
48
49                         return ctor;
50                 }
51         }
52 }
53