C# constructors

C# constructors

A constructor is what creates the instance of a class(also known as a object). They essentially define the default values for a object, even if you don’t specifically make a constructor you will still have the parameter-less constructor, which is essentially the default that every class will automatically have. It will set all global variables that aren’t defined to the default definition of their type.

A constructor is made by doing:

accessmodifier variabletype variableName;

accessmodifier variabletype2 variableName2;

public ClassName(parametertype1 parameterName, parametertype2 ParameterName2)

{

variableName = parameterName;

variableName2 = parameterName2;

}

It’s easiest to think of a constructor as a kind of method where it is used to define a object( aka giving values to global variables for that instance of the class), and it being the same name as the name of its type( with it’s type being the class you are making a instance of).

There are also static constructors which basically defines the static global variables.

So something like:

accessmodifier static variabletype variableName;

static ClassName()

{

variableName = value;

}

Notice that the static constructor is parameter-less since, the static variables shouldn’t be changing in the code based on which instance is being used.

You call a constructor by creating a object of that type with the correct arameters, in other words like this:

ClassName objectName = new ClassName( valueForParameter, valueForParameter2);

The valueForParameter can of course be a variableName or a value(as in say the parameter type was int you could but 12 or 15 or you could put the int variable myInt that you have already assigned a value).

There is more information on the Microsoft docs guide.

One thought on “C# constructors

Comments are closed.