Constructors
A constructor is the setup that runs automatically when a new object is created, like assembling and charging a toy as it comes out of the box. It gives the object its starting values.
In this page:
Syntax
class ClassName
{
public ClassName(type parameter)
{
// initialize fields
}
}
ClassName objectName = new ClassName(argument);
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Giving the constructor a return type, which makes it an ordinary method.
- Defining a parameterized constructor and then calling
new Person(), which fails because the default one is no longer generated. - Not calling
this(...)orbase(...)when needed, leaving fields uninitialized.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: