logo
CSharp_Prog_Guide

Рассмотрение кода

В данном примере необходимо передать параметры по ссылке для оказания влияния на переменные в вызывающей программе. Если удалить ключевое слово ref как из заголовка метода, так и из вызова метода, то вызывающая программа изменена не будет.

Constructors

Whenever a class or struct is created, its constructor is called. A class or struct may have multiple constructors that take different arguments. Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read.

If you do not provide a constructor for your object, C# will create one by default that instantiates the object and sets member variables to the default values. Static classes and structs can also have constructors.

Using Constructors

Constructors are class methods that are executed when an object of a given type is created. Constructors have the same name as the class, and usually initialize the data members of the new object.

In the following example, a class named Taxi is defined by using a simple constructor. This class is then instantiated with the new operator. The Taxi constructor is invoked by the new operator immediately after memory is allocated for the new object.

public class Taxi

{

public bool isInitialized;

public Taxi()

{

isInitialized = true;

}

}

class TestTaxi

{

static void Main()

{

Taxi t = new Taxi();

System.Console.WriteLine(t.isInitialized);

}

}

A constructor that takes no parameters is called a default constructor. Default constructors are invoked whenever an object is instantiated by using the new operator and no arguments are provided to new.