Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Class Constructors | Introduction to Object-Oriented Programming (OOP)
C# Beyond Basics
course content

Contenido del Curso

C# Beyond Basics

Class Constructors

A class constructor is the same as a struct constructor. It is a method which is executed when an object is created.

The syntax for creating a constructor is the following:

cs

index

For-example:

cs

index

You can see from the output that the Console.WriteLine statement inside the Player constructor is executed every time a new object is created.

Following is an example code from the Struct Constructors chapter. The term static is explained in the comments as it is more relevant here however it is not necessary to completely understand it as this concept will be explained in detail in later sections.

cs

index

In order to convert the Player struct into a class, all we need to do is to change the term struct to class:

cs

index

Similarly, we can have constructors with some arguments as well. Usually, this method is used to make the initialization of class fields easier:

cs

index

At this point, we have covered most of the basic concepts of the Classes, and judging from the syntax and behavior, Classes seem to be exactly the same as Structs, however, that is not actually the case. As stated in the first chapter of this section, Structs are a limited version of Classes that only provide a basic functionality on the other hand the features of Classes are much more complex and broad. In this section we have covered all the features that are similar between Classes and Structs. In the next two sections we will learn all the intricacies of classes and object-oriented programming.

1. When is a constructor method called?
2. What will be the name of a constructor method in a class called "Animal"?
3. Which keyword is used before a constructor name?

When is a constructor method called?

Selecciona la respuesta correcta

What will be the name of a constructor method in a class called "Animal"?

Selecciona la respuesta correcta

Which keyword is used before a constructor name?

Selecciona la respuesta correcta

¿Todo estuvo claro?

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