logo
Учебник_ПОА

Constructors

Every class has a constructor: a method that shares the same name as the class. The constructor is called when an object is created based on the class definition. Constructors typically set the initial values of variables defined in the class. This is not necessary if the initial values are to be zero for numeric data types, false for Boolean data types, or null for reference types, as these data types are initialized automatically.

You can define constructors with any number of parameters. Constructors that do not have parameters are called default constructors. The following example defines a class with a default constructor and a constructor that takes a string, and then uses each:

class SampleClass

{

string greeting;

public SampleClass()

{

greeting = "Hello, World";

}

public SampleClass(string message)

{

greeting = message;

}

public void SayHello()

{

System.Console.WriteLine(greeting);

}

}

class Program

{

static void Main(string[] args)

{

// Use default constructor.

SampleClass sampleClass1 = new SampleClass();

sampleClass1.SayHello();

// Use constructor that takes a string parameter.

SampleClass sampleClass2 = new SampleClass("Hello, Mars");

sampleClass2.SayHello();

}

}