AnotherClass { MyClass _myClass {get; set} = new(); }
This is a property declaration with an auto-implemented property initialiser.
_myClass
is a property of type
MyClass
and it's initialised with a new instance of
MyClass
when
AnotherClass
is instantiated.
AnotherClass { MyClass _myClass = {get;set;} }
This is not valid C#. It looks like you are trying to declare a property. It should look like this
MyClass _myClass { get; set; }
AnotherClass { MyClass _myClass = new(); }
This is a field declaration.
_myClass
is a field of type
MyClass
and it's initialised with a new instance of
MyClass
when
AnotherClass
is instantiated
Fields and properties typically have different access modifiers in C#.
AnotherClass { MyClass _myClass; }
This is a field declaration without initialisation.
_myClass
is a field of type
MyClass
, but it's not initialised, so its value will be
null
until it's explicitly set.
Essentially your question is about fields vs. properties and instantiation at the time of declaration (or not).
Fields are typically used for internal use while properties expose fields to the outside world.
Auto-implemented properties (like in the first example) are a shorthand syntax that automatically creates a private, anonymous backing field that can only be accessed through the property's
get
and
set
accessors.
With regards to your question and the clarification given in your comment below :
In Case a) I also wonder how I can hand over parameters to the constructor, when they do not yet exist at the time MyClass is instantiated.
That looks circular ? You seem to want to create an instance of
MyClass
that contains an instance of
AnotherClass
but
AnotherClass
also contains an instance of
MyClass
and since you are using the
this
keyword then it would seem that the '
two' instances of
MyClass
are actually one in the same. Are you trying to allow a nested class to use the properties, methods and functions of its parent? I would recommend that you ask a separate question detailing what you are trying to achieve and ask how you might go about it.
M