
Untitled
By: a guest on
Jun 22nd, 2012 | syntax:
None | size: 1.40 KB | hits: 10 | expires: Never
C# object initialization of read only collection properties
using System;
using System.Collections.Generic;
using NUnit.Framework;
namespace WF4.UnitTest
{
public class MyClass
{
private List<string> _strCol = new List<string> {"test1"};
public List<string> StringCollection
{
get
{
return _strCol;
}
}
}
[TestFixture]
public class UnitTests
{
[Test]
public void MyTest()
{
MyClass c = new MyClass
{
// huh? this property is read only!
StringCollection = { "test2", "test3" }
};
// none of these things compile (as I wouldn't expect them to)
//c.StringCollection = { "test1", "test2" };
//c.StringCollection = new Collection<string>();
// 'test1', 'test2', 'test3' is output
foreach (string s in c.StringCollection) Console.WriteLine(s);
}
}
}
MyClass c = new MyClass
{
StringCollection = { "test2", "test3" }
};
MyClass tmp = new MyClass();
tmp.StringCollection.Add("test2");
tmp.StringCollection.Add("test3");
MyClass c = tmp;
// this WON'T work, as we can't assign to the property (no setter)
MyClass c = new MyClass
{
StringCollection = new StringCollection { "test2", "test3" }
};
c.StringCollection = new List<string>();