BBR
BBR

Reputation: 131

Deserialization error - object reference not set

I am trying to deserialize an xml string in c#3.5, the code below does work in c# 4.0. When I try to run in the code in c#3.5 I get an Object reference not set to an instance of an object exception when the code tries in initialize the XmlSerializer.

Any help would be appreciated.

string xml = "<boolean xmlns=\"http://schemas.microsoft.com/2003/10/serialization/\">false</boolean>";
var xSerializer = new XmlSerializer(typeof(bool), null, null,
             new XmlRootAttribute("boolean"),
             "http://schemas.microsoft.com/2003/10/serialization/");

             using (var sr = new StringReader(xml))
            using (var xr = XmlReader.Create(sr))
            {
                var y = xSerializer.Deserialize(xr);
            }

System.NullReferenceException was unhandled
  Message="Object reference not set to an instance of an object."
  Source="System.Xml"
  StackTrace:
       at System.Xml.Serialization.XmlSerializer..ctor(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, String defaultNamespace, String location, Evidence evidence)
       at System.Xml.Serialization.XmlSerializer..ctor(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, String defaultNamespace)
       ....
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

Upvotes: 2

Views: 3196

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064204

It looks like in .NET 3.5 it doesn't like the Type[] extraTypes to be null. Just pass an empty Type[] instead, for example new Type[0], or just simply:

var xSerializer = new XmlSerializer(typeof(bool), null, Type.EmptyTypes, 
                 new XmlRootAttribute("boolean"),
                 "http://schemas.microsoft.com/2003/10/serialization/");

As a side note: when creating XmlSerializer instances using non-trivial constructors (like this one), it is very important to cache and re-use the serializer - otherwise it'll generate an in-memory assembly per serializer, which is a: bad for performance, but b: causes a severe memory leak (assemblies cannot be unloaded).

Upvotes: 1

Related Questions