Private-setter properties in C# 3.0 object initialization

No there is no way to achieve this. Object Initializers only allow you to access fields and properties which would be otherwise accessible outside the initializer.

Your best option is to use a constructor which explicitly sets these properties.


Private set on myName means you can only initialize (set) it from something that is a member of MyClass. For example:

        public class MyClass {
        public string myName { get; private set; }
        public string myId { get; set; }

        public static MyClass GetSampleObject() {
            MyClass mc = new MyClass
            {
                myName = "Whatever",
                myId = "1234"
            };
            return mc;
        }
    }

(I copied and pasted your initialization code into the GetSampleObject method).

But if you try to set it outside MyClass, you get a compiler error, because private is private.


If they need to be set at initialisation then consider passing them as args to the constructor