Constructors (Instance Constructor)

Constructors are used to create and initialize instances. If the class does not have a constructor, a default parameterless constructor is automatically generated and the default values are used to initialize the object fields (for example, an int is initialized to 0).

When a class constructor is invoked a new object is created:

Point myPoint = new Point();

The class constructor can invoke the constructor of the base class through the initializer:

public Cylinder(double radius, double height) : base(radius, height)

The class constructor can also invoke another constructor from the same class by using the keyword this:

public Point() : this(0,20)

In C#, functions are not virtual by default but (aside from constructors) can be explicitly declared as virtual.

Struct constructors

Struct constructors are similar to class constructors, except for the following differences:
  • Structs cannot contain explicit parameterless constructors. Struct members are automatically initialized to their default values.
  • A struct cannot have an initializer in the form : base (argument-list).

Static Constructors
  • A given class (or structure) may define only a single static constructor.
  • A static constructor executes exactly one time, regardless of how many objects of the type are created.
  • A static constructor does not take an access modifier and cannot take any parameters.
  • The runtime invokes the static constructor when it creates an instance of the class or before accessing the first static member invoked by the caller.
  • The static constructor executes before any instance-level constructors.

Related Post:

No comments:

Post a Comment