Initializing Fields in Constructors
Learn how to initialize fields in C# constructors and define multiple constructors with different parameter sets for a class.
We'll cover the following
In C#, constructors play a vital role in initializing fields when an instance of a class is created. Let’s explore how constructors set initial values for fields, including read-only fields. We’ll also learn how to define multiple constructors to provide flexibility in initializing objects.
Fields in constructors
Fields often need to be initialized at runtime. We do this in a constructor that will be called when we make an instance of the class using the new
keyword.
What are the signatures of the constructors that all exceptions should have?
The signatures of the three constructors that all exceptions should have are shownin the following list:
A constructor with no parameters.
A constructor with a string parameter, usually named message.
A constructor with a string parameter, usually named message, and an Exceptionparameter, usually named innerException.
Constructors execute before any fields are set by the code that is using the type:
Step 1: In Person.cs
, add statements after the existing read-only HomePlanet
field to define a second read-only field and then set the Name
and Instantiated
fields in a constructor, as shown in the following code:
Get hands-on with 1400+ tech skills courses.