Home
C#
Constructor Examples
This page was last reviewed on May 7, 2024.
Dot Net Perls
Constructor. 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.
class
Destructor
String Constructor
First example. 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.
Part 1 Here we invoke the constructor (with the new keyword) to create new instances of the Widget type.
Part 2 The Widget constructor receives the integer size parameter. It assigns the field in the 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
Base constructor. 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.
base
Here We have a Parrot class that derives from the Bird class (which derives from object).
Info The Parrot constructor has a "base" constructor call (which means the Bird constructor is called when a Parrot is created).
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:::
This constructor. 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.
Tip Making code easy to read and understand should be a design goal for many classes.
Tip 2 The this-keyword allows code to be shared between the constructors. Constructor initializers are useful in nontrivial classes.
Detail The Mouse class has 2 constructors. The first constructor has no parameters. It calls into the second constructor with "this."
Here The 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
Default constructor. Classes have default constructors. These constructors are injected into all class declarations that do not introduce other constructors. This simplifies syntax.
Info This program shows how the default constructor is added to all classes that have no explicitly defined constructors.
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
Notes, default constructor. In .NET, code is compiled into an intermediate representation. The default constructors in this program are added there.
Intermediate Language
Here We see the intermediate language of the default constructor that was silently added.
Note This constructor is invoked in the 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 constructor. Public constructors allow a class to be instantiated from an external location in a program. Most constructors will be in the public accessibility domain.
public, private
Note This class has a custom constructor that receives a parameter. The constructor uses parameter validation.
ArgumentException
Note 2 Classes without a public constructor will have an "implicit public constructor" one added automatically by the C# compiler.
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
Private constructor. 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.
Tip The private constructor ensures that it is impossible for the class to be instantiated directly from external classes.
Here This class has a private constructor and 2 fields. The constructor initializes the public int field A to be equal to 5.
Important A private constructor can enforce the singleton design pattern. External code (without reflection) can never create an instance.
Reflection
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
Expression-bodied constructor. A shorter syntax form can be used to specify a constructor. We can use an expression for the constructor's body.
Here Look at the Dog constructor. It initializes the "paws" field to the value 4. Be careful not to use surrounding parentheses here.
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
Primary constructor. It is possible to specify the fields of a class as an argument list to the class definition. This is called primary constructor syntax.
Here We want a 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
Review. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 7, 2024 (new example).
Home
Changes
© 2007-2024 Sam Allen.