Constructors
In this page:
Constructors
A constructor is a special method that runs automatically when an object is created, typically used to initialize its fields. It shares the class's name and has no return type. If you don't define one, C# provides a default parameterless constructor.
Note: Use constructor parameters to force callers to provide required data at creation time.
Example: Constructors
using System;
class Person
{
public string Name;
public int Age;
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
class Program
{
static void Main(string[] args)
{
Person p = new Person("Maya", 28);
Console.WriteLine($"{p.Name} is {p.Age} years old");
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: