CSharp - Type Creation Instance Constructors

Introduction

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.

Demo

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

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

Result

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

Quiz

Example