Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# object initialization of read only collection properties

Tags:

c#

c#-3.0

c#-4.0

For the life of me, I cannot figure out what is going on in the example piece of C# code below. The collection (List) property of the test class is set as read only, but yet I can seemingly assign to it in the object initializer.

** EDIT: Fixed the problem with the List 'getter'

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);
        }
    }
}
like image 465
markdb314 Avatar asked Apr 13 '11 08:04

markdb314


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


2 Answers

This:

MyClass c = new MyClass
{
    StringCollection = { "test2", "test3" }
};

is translated into this:

MyClass tmp = new MyClass();
tmp.StringCollection.Add("test2");
tmp.StringCollection.Add("test3");
MyClass c = tmp;

It's never trying to call a setter - it's just calling Add on the results of calling the getter. Note that it's also not clearing the original collection either.

This is described in more detail in section 7.6.10.3 of the C# 4 spec.

EDIT: Just as a point of interest, I was slightly surprised that it calls the getter twice. I expected it to call the getter once, and then call Add twice... the spec includes an example which demonstrates that.

like image 55
Jon Skeet Avatar answered Sep 19 '22 15:09

Jon Skeet


You aren't calling the setter; you are essentially calling c.StringCollection.Add(...) each time (for "test2" and "test3") - it is a collection initializer. For it to be the property assignment, it would be:

// this WON'T work, as we can't assign to the property (no setter)
MyClass c = new MyClass
{
    StringCollection = new StringCollection { "test2", "test3" }
};
like image 39
Marc Gravell Avatar answered Sep 20 '22 15:09

Marc Gravell