Constructors — RexDac Academy

RexDac AcademyTechnical notes · Some prior knowledge helps
0%Published notes read · this device

Level 4 — Classes

Constructors

Original notes by SunDiaL · View English source

Constructors are a special type of methods that do not have a name and always return an object of your class. Their purpose is construct an object of your class. Other ways of saying this that you'll hear is "to create an object" or to "to instantiate an object".

Defining a constructor

public class ExampleClass()
{
	public ExampleClass()
	{
	
	}
}

Note: you can define multiple constructors -> constructor overloading.

Note 2: C# automatically creates an empty constructor for all classes, so unless yours does something or you want to limit access to it, it can be omitted.

Invoking a constructor

Invoking a constructor is done with the new keyword.

public void Main()
{
	ExampleClass myVariable = new ExampleClass();
}