Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Struct Constructors | Structs & Enumerators
C# Beyond Basics
course content

Contenido del Curso

C# Beyond Basics

C# Beyond Basics

1. Additional Structures & File Handling
2. Structs & Enumerators
3. Introduction to Object-Oriented Programming (OOP)
4. OOP Essentials
5. OOP Principles

bookStruct Constructors

A constructor is a method which is automatically executed when a new object is created.

The syntax of a constructor is somewhat similar to that of a method, we simply omit the returnType as a constructor doesn't return any value:

cs

index

copy
1234567891011
struct structureName { // ... fields (optional) public structureName(parameter1, parameter2, ...) { // code } // ... methods (optional) }

The following points are important to note about the constructor syntax:

  1. The constructor name is the same as the structure name.
  2. A constructor does not have any return value.

The following program demonstrates how the constructor is called whenever an object is created:

cs

index

copy
12345678910111213141516171819
using System; struct Player { public Player() { Console.WriteLine($"New Player Object Created"); } } class Program { static void Main(string[] args) { Player player1 = new Player(); Player player2 = new Player(); Player player3 = new Player(); } }

Let's add a field to Player called id which will be a unique identifier of that object so each object will have a different value for id. It will start from 0 and will increment. To achieve that we will create a global variable called totalPlayers.

cs

index

copy
12345678910111213141516171819202122232425262728
using System; class ConsoleApp { // We use the term 'static' when declaring variables directly under class // This will be explained in much more detail in later sections. public static int totalPlayers = 0; // This time we create put the struct inside the `ConsoleApp` class // This is to be able to use the `totalPlayers` variable easily. struct Player { public int id; public Player() { id = totalPlayers++; Console.WriteLine($"New Player Object Created With ID {id}"); } } static void Main(string[] args) { Player player1 = new Player(); Player player2 = new Player(); Player player3 = new Player(); } }

In the above code, we placed the struct inside the Program class to be able to access the 'totalPlayers' variable from inside the constructor.

We can pass data into a constructor when creating a new object using the following syntax:

Following is a practical example of the usage:

cs

index

copy
1234567891011121314151617181920212223242526272829
using System; struct Coordinate3D { public double x; public double y; public double z; public Coordinate3D(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } public void displayValue() { Console.WriteLine($"{this.x}, {this.y}, {this.z}"); } } class ConsoleApp { static void Main(string[] args) { Coordinate3D coord1 = new Coordinate3D(3, 5, 7); coord1.displayValue(); } }

Let's look at the code step by step.

First, we created a constructor and inside the constructor we assigned the passed values x, y, z to the fields x, y and z:

cs

index

copy
123456
public Coordinate3D(double x, double y, double z) { this.x = x; this.y = y; this.z = z; }

Inside the Main method, we created a new Coordinate3D object and passed 3, 5, and 7 as x, y and z through the constructor.

cs

index

copy
1
Coordinate3D coord1 = new Coordinate3D(3, 5, 7);

To confirm whether the fields were successfully initiated by the constructor or not, we used the displayValue method:

cs

index

copy
1
coord1.displayValue();

The output proved that the fields were successfully updated.

The constructors are very useful when we want to initiate objects with some data or for performing some initial operations when an object is created.

When are constructors called?

When are constructors called?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 8
We're sorry to hear that something went wrong. What happened?
some-alt