While developing a class library for communicating with an external database over JSON, an interesting problem arose where an upcast of an object instance resulted in one of its previously non-null members appear as null.
Many a hairs have been torn out while trying to figure out the cause of this oddity but so far I have been unsuccessful in finding a sane explanation.
Here is an example of the issue:
using System;
namespace Test
{
public class Program
{
static void Main(string[] args)
{
Descendant d = new Descendant();
d.Attributes.ToString(); // Everything fine here
Ancestor a = (Ancestor)d;
a.Attributes.ToString(); // NullPointerException
}
}
class Ancestor
{
public interface IAttributes { }
public IAttributes Attributes;
}
class Descendant : Ancestor
{
public new DescendantAttributes Attributes;
public Descendant()
{
this.Attributes = new DescendantAttributes();
}
public class DescendantAttributes : IAttributes
{
public string Name = "";
}
}
}
Error message: System.NullReferenceException was unhandled at Test.Program.Main(String[] args) in D:\Code\c#\Test\Program.cs:line 12
.NET version: 4.0
Environment: 64-bit Windows 2008 R2, Visual Studio 2010
Why does it happen? I mean, unless its a bug there probably is a design rationale behind it. What kind of situations would warrant CLR to consider a previously non-null member of an instance as null after an upcast?