Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting properties with {} braces when instantiating

Anyone knows why the following will not compile? The setter for ID is supposed to be private for both classes, so why can we instantiate ClassA but not ClassB?

public class ClassA {
    public string ID { get; private set; }

    public void test() {
        var instanceA = new ClassA() { ID = "42" };
        var instanceB = new ClassB() { ID = "43" };
    }

    public class ClassB {
        public string ID { get; private set; }
    }
}

Thanks

like image 618
Erwin Mayer Avatar asked Dec 12 '22 12:12

Erwin Mayer


2 Answers

test() is a member of ClassA, so it has access to the private members (and the setter) of A. It does not have access to the private members or setters of ClassB, hence the error on instanceB but not instanceA.

For more on accessibility of private members, I encourage you to see this answer on a related question.

like image 116
Anthony Pegram Avatar answered Dec 27 '22 04:12

Anthony Pegram


Your Test method is in Class A so that can be accessed.

like image 24
keyboardP Avatar answered Dec 27 '22 04:12

keyboardP