A constructor is a method that runs when a new instance of a class is created.
The job of the constructor is to create the object specified by a class and to put it into a valid state.
Constructors can be marked as public, private, protected, internal or protected internal.
If a field is marked as read-only then the only place in which it can be assigned is in the constructor.
A constructor is basically the class initialisation process
Two forms are supported
(1) inline field initializers
(2) constructors (constructor chaining also supported)

Instance and Static constructors supported
Static Constructors - called before types first use (also called type initializer)
Instance Constructors - called per-object allocation
A Copy Constructor creates a new object by copying variables from an existing object of the same type

Static Constructor

A static constructor is used to initialise any static fields, properties or events.
A static constructor can be used to perform an action that only needs to be performed once
It is called automatically before the first instance is created or any static members are referenced.
This allows you to control the initialization of static member data
Also referred to as a type initializer
A static constructor does not require any access modifier.
A class can only have one static constructor with no parameters.

public class MyClass 
   static MyClass()

Private Constructors

These are used to prevent creating instances of a class that do not have any instance fields or methods.
This is generally used in classes that contain only static members
It a class has one or more private constructors and no public constructor then it cannot be instantiated

© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext