Constructors
Lesson 5 of 12 in Coddy's Basics of Classes and Objects in C# course.
A constructor is a special method that is used to initialize objects. The constructor is called when an object of a class is created. (We will see this in action in couple of lessons)
To create a constructor, use:
class MyClass {
public MyClass() {
}
}As you see, the constructor does not have a return type like any other method, and it has the same name as the class name.
A common use of the constructor method is to initiate values into the class fields, for example:
class Point {
int x = 0;
int y = 0;
public Point(int newX, int newY) {
x = newX;
y = newY;
}
}In the above example, we initiate the values of x and y on the creation of an object of type Point.
Note, you can refer to class methods and attribute using this keyword, like this:
class Point {
int x = 0;
int y = 0;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}In the above example, it's important to use this keyword because the name of the arguments are same as the attributes!
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a class named Person with two public attributes: name (string) and age (integer), and create a constructor that initializes both attributes with arguments from the constructor method.
Try it yourself
// Write code hereAll lessons in Basics of Classes and Objects in C#
1Introduction
Introduction