Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 22nd, 2012  |  syntax: None  |  size: 1.40 KB  |  hits: 10  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. C# object initialization of read only collection properties
  2. using System;
  3. using System.Collections.Generic;
  4. using NUnit.Framework;
  5.  
  6. namespace WF4.UnitTest
  7. {
  8.     public class MyClass
  9.     {
  10.         private List<string> _strCol = new List<string> {"test1"};
  11.  
  12.         public List<string> StringCollection
  13.         {
  14.             get
  15.             {
  16.                 return _strCol;
  17.             }
  18.         }
  19.     }
  20.  
  21.     [TestFixture]
  22.     public class UnitTests
  23.     {
  24.         [Test]
  25.         public void MyTest()
  26.         {
  27.             MyClass c = new MyClass
  28.             {
  29.                 // huh?  this property is read only!
  30.                 StringCollection = { "test2", "test3" }
  31.             };
  32.  
  33.             // none of these things compile (as I wouldn't expect them to)
  34.             //c.StringCollection = { "test1", "test2" };
  35.             //c.StringCollection = new Collection<string>();
  36.  
  37.             // 'test1', 'test2', 'test3' is output
  38.             foreach (string s in c.StringCollection) Console.WriteLine(s);
  39.         }
  40.     }
  41. }
  42.        
  43. MyClass c = new MyClass
  44. {
  45.     StringCollection = { "test2", "test3" }
  46. };
  47.        
  48. MyClass tmp = new MyClass();
  49. tmp.StringCollection.Add("test2");
  50. tmp.StringCollection.Add("test3");
  51. MyClass c = tmp;
  52.        
  53. // this WON'T work, as we can't assign to the property (no setter)
  54. MyClass c = new MyClass
  55. {
  56.     StringCollection = new StringCollection { "test2", "test3" }
  57. };
  58.        
  59. c.StringCollection = new List<string>();