We use constructors in C# to create classes. Constructors help keep programs simple by making "initialize" methods standard.
In the C# language, a constructor carries the same name as its class
. We invoke a constructor with "new." A constructor can have multiple (overloaded) versions.
The Widget class
here has a public constructor with an int
parameter. To create a Widget, we must call this constructor with an int
argument.
class
to the argument.using System; class Widget { int _size; public Widget(int size) { // Part 2: execute constructor logic. this._size = size; } } class Program { static void Main() { // Part 1: invoke constructor. Widget widget1 = new Widget(10); Widget widget2 = new Widget(20); Console.WriteLine("DONE"); } }DONE
If we have to add a constructor to a derived class
, the base keyword is often useful. This will have the derived constructor invoke the base class
constructor.
class
that derives from the Bird class
(which derives from object).using System; public class Bird { public Bird(int value) { Console.WriteLine($"Bird() called with {value}"); } } public class Parrot : Bird { public Parrot(int value) : base(value) { Console.WriteLine($"Parrot called with {value}"); } } class Program { static void Main() { Parrot parrot = new Parrot(450); Console.WriteLine(":::DONE:::"); } }Bird() called with 450 Parrot called with 450 :::DONE:::
Sometimes in a class
we have many constructors. We can use "this" to have one constructor invocation call another constructor method. This reduces code bloat.
this
-keyword allows code to be shared between the constructors. Constructor initializers are useful in nontrivial classes.class
has 2 constructors. The first constructor has no parameters. It calls into the second constructor with "this."this
-keyword instructs the compiler to insert a call to the specified constructor at the top of the first constructor.using System; class Mouse { public Mouse() : this(-1, "") { // Uses constructor initializer. } public Mouse(int weight, string name) { // Constructor implementation. Console.WriteLine("Constructor weight = {0}, name = {1}", weight, name); } } class Program { static void Main() { // Test the 2 constructors for Mouse type. Mouse mouse1 = new Mouse(); Mouse mouse2 = new Mouse(10, "Sam"); } }Constructor weight = -1, name = Constructor weight = 10, name = Sam
Classes have default constructors. These constructors are injected into all class
declarations that do not introduce other constructors. This simplifies syntax.
using System; class Test // Has default parameterless constructor { public int Value { get; set; } } class Program { static void Main() { // Call the default constructor. Test test = new Test(); test.Value = 1; Console.WriteLine(test != null); } }True
In .NET, code is compiled into an intermediate representation. The default constructors in this program are added there.
Main
method. It calls into the base class
constructor, which is the System.Object
constructor..method public hidebysig specialname rtspecialname instance void .ctor() cil managed { .maxstack 8 L_0000: ldarg.0 L_0001: call instance void [mscorlib]System.Object::.ctor() L_0006: ret }
Public constructors allow a class
to be instantiated from an external location in a program. Most constructors will be in the public accessibility domain.
class
has a custom constructor that receives a parameter. The constructor uses parameter validation.using System; class Test { public Test(int a) { if (a == 0) { throw new ArgumentException("Error", "a"); } } } class Program { static void Main() { Test test = new Test(5); Console.WriteLine("DONE"); } }DONE
A private constructor cannot be externally called. It can ensure higher-quality code. It forces the class
to provide a controlled and unified access pattern.
class
to be instantiated directly from external classes.class
has a private constructor and 2 fields. The constructor initializes the public int
field A to be equal to 5.using System; public sealed class Test { public static readonly Test Instance = new Test(); // Singleton pattern. public int A; // Instance field. private Test() // This is the private constructor. { this.A = 5; } } class Program { static void Main() { // We can access an instance of this object that was created. // ... The private constructor was used. Test test = Test.Instance; // Use the class instance. Console.WriteLine(test.A); test.A++; Console.WriteLine(test.A); } }5 6
A shorter syntax form can be used to specify a constructor. We can use an expression for the constructor's body.
using System; class Dog { int paws; // Expression-bodied constructor. // ... Do not use parentheses around the right side. public Dog() => paws = 4; // Expression-bodied property. public int Paws { get => paws; } } class Program { static void Main() { Dog dog = new Dog(); // Use property to get value of paws. Console.WriteLine(dog.Paws); } }4
It is possible to specify the fields of a class
as an argument list to the class
definition. This is called primary constructor syntax.
class
Bird with a color string
field, and a feathers int
field.using System; class Bird(string color, int feathers) { public void Display() { // Access fields from primary constructor syntax. var colorUppercase = color.ToUpper(); Console.WriteLine($"Color = {colorUppercase}, Feathers = {feathers}"); } } class Program { static void Main() { // Use primary constructor class. var bird = new Bird("blue", 1000); bird.Display(); } }Color = BLUE, Feathers = 1000
There are many kinds of constructors in the C# language. We use constructors to make code clearer—with them, we formalize how objects are created.