Constructor (C#)

A constructor is a special method that runs automatically when you create an object with new. It sets up the object's starting state, usually by assigning its fields and properties.

C#

A constructor has the same name as its class and no return type. You can give it parameters so callers supply initial values when they create the object.

If you don't write one, C# provides a default parameterless constructor. You can define several constructors with different parameters (overloading).

Syntax

public ClassName(parameters) { ... }

Examples

C#

class Person
{
    public string Name;
    public Person(string name)
    {
        Name = name;
    }
}

var p = new Person("Ada");
Console.WriteLine(p.Name);

Output:

Ada

Learn it in a lesson

See also

Back to the Dictionary