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
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.
Your Test
method is in Class A
so that can be accessed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With