- This is the order of initialization when instantiating any class:
- Static Fields (first time class access only: static members or first instance)
- Static Constructor (first time class access only: static members or first instance)
- Instance fields (each instance)
- Instance constructor (each instance)
Accessibility Options
public
: all code can access member
private
: only code within the same type can access member
protected
: code within type or subtype can access member
internal
: code within the same assembly can access member
protected internal
: code within the same assembly, within the same type, or within a subtype can access member
Allowed Levels of Accessibility
- Class: can be public or internal (default is internal) [can only be public if parent class is public]
- Namespace: always public
- Class members: can be public, private, protected, internal or protected internal (default is private)
- Struct members: can be public, private, or internal (default is private)
- Interface members: always public
- Enumeration members: always public
Constructors
- Internally, the interaction between the new operator and the constructor is as follows:
- The new operator retrieves memory from the memory manager and calls the specified constructor, passing the initialized memory to the constructor.
- Next, the remainder of the constructor chain executes, passing around the initialized memory between constructors.
- When execution completes on the constructor, the new operator returns the memory reference, now referring to the memory in its initialized form.
- When an exception occurs while initializing another object in a constructor, the runtime will automatically wrap the exception into a
TypeInitializationException
.
Default Constructors
- If a class has no explicitly defined constructor, then the C# compiler adds one during compilation.
- This constructor takes no parameters and is, therefore, the default constructor by definition.
- As soon as you add an explicit constructor with parameters to a class, the C# compiler no longer provides a default constructor.
- It is possible for programmers to define a default constructor explicitly.