C-Sharp C#
Constructors
ClassesIn C# classes, a constructor is a special method inside a class that runs automatically when you create an object with new. It sets up the object with initial values, so you don't have to assign them one by one.
A constructor has the same name as the class and no return type.
Constructors - A
Let's add a default constructor to our Person class. A "default" constructor is one that takes no parameters. This will set up default values for each Person object we create.
class Person {
public string Name;
public int Age;
public double Height;
// Default constructor
public Person() {
Name = "NO NAME";
Age = 0;
Height = 0.0;
}
}With this default constructor, every time we create a new Person without giving it any values, it starts with these safe defaults instead of empty or zero values we never chose on purpose.
Let's see an example:
Person p = new Person(); // Calls the default constructor
Console.WriteLine($"{p.Name} - {p.Age} - {p.Height}");OUTPUT:
NO NAME - 0 - 0Constructors - B
We can also create a constructor that takes parameters to set the name, age, and height when we create a Person. Here we'll use this. so it's clear which Name we mean the class's field or the parameter.
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 4 more lessons in C-Sharp C#.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.