The following code throws an exception. If there is no easy answer or stuff to check, I'll try to produce something that reproduces the error (though I don't know where to upload it).
public static XMLobj Load(string FileName)
{
if (File.Exists(FileName) == false)
{
return null;
}
IRDnet.XMLobj def;
XmlSerializer xmlser = new XmlSerializer(typeof(IRDnet.XMLobj));
System.IO.Stream stream = File.OpenRead(FileName);
object o = xmlser.Deserialize(stream);
// o appears to be of correct type in the quick watch.
IRDnet.XMLobj def2 = o as IRDnet.XMLobj;
// def2 is "undefined" (as operator rejected o)
def = (IRDnet.XMLobj)o;
// Throws InvalidCastException with no InnerException.
stream.Close();
return def;
}
The strange thing is that "o" appears to be of correct type if I break just before the exception is thrown:
o {IRDnet.XMLobj} System.Object
And the object casts just fine in the quickwatch window. Values are easily inspected.
It is executed from the same project that it is part of. So, no loading contexts. FYI: the static method is part of the XMLobj class if that's relevant. Is there some other criteria for a successful cast that I'm not aware of? Any code that gets implicitly executed?
I've checked that reflector produces the equivalent code to make sure that nothing was lost in compiler optimization.
Any clues, people? I'm stumped. I even hoped that just writing this question would make me think twice on something completely obvious.