Setting properties using {} curly brackets when instantiating

Does anyone know why the following will not compile? The installer for ID is supposed to be private to both classes, so why can we create an instance of 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

+4
source share
3 answers

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

For more information on the availability of private members, I recommend that you see this answer on the relevant question.

+10
source

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

+3
source

Class B is inside Class A , A cannot access private members of B just because of composition.

0
source

All Articles