CSharp - Type Creation Instance Constructors


Constructors are used to initialize a class or struct.

A constructor is defined like a method.

The constructor has the same name with its type.

The constructor does not have a return type.


using System;
class MainClass//from  w w  w.j av a  2 s  .  c o m
   public static void Main(string[] args)
       Person p = new Person ("book2s.com");   // Call constructor

class Person
       public string name;            // Define field
       public Person (string n)        // Define constructor
         name = n;                    // Initialization code (set up field)


Instance constructors allow the following modifiers:

Modifiers Value
Access modifiers public internal private protected
Unmanaged code modifiers unsafe extern

You can write single-statement constructors as expression-bodied members:

public Person(string n) => name = n;

Related Topics