NullReferenceException
次のコードでランタイム例外が発生しました。
public class Container
{
public IList<string> Items { get; set; }
}
class Program
{
static void Main(string[] args)
{
var container = new Container() { Items = {"Test"} };
}
}
コンパイラがインターフェイスインスタンスを作成できなかったのは当然ですが、コンパイル時ではなく、ランタイム例外が発生しました。この動作をさらに調査すると、さらに混乱しました。
var container = new Container() { Items = {} }; //Legal, Items is null after initialization
var container = new Container() { Items = { "Test" } }; //Legal, throws exception
container.Items = {}; //Illegal doesn't compile
container.Items = {"Test"}; //Illegal doesn't compile
これはある種のバグですか、それとも私は何かを理解していませんか?そして、私は.netFramework4.0を使用しています