Initialization in classes. Ways to initialize data in the class. Initialization of variables of basic types. Initialization using object initializers 

Initialization in classes. Ways to initialize data in the class. Initialization of variables of basic types. Initialization using object initializers 


Contents


1. What are the ways to initialize data in a class when creating a class object?

In C#, a class object is created using the new operator. During creation, the internal data (variables) of a class can be initialized in one of the following ways:

  • by assigning a class variable the desired value when it is declared (immediate initialization). This method is used only for variables of base types. If it is necessary to initialize a class object, then an object initializer is used;
  • with the help of a class constructor;
  • with the help of object initializer. This method is used for class objects or structure variables. In this case, the class data must be declared as public.

 

2. The general form of the initialization of the internal data of a class using the direct assignment of the desired value

The internal data of a class can be initialized immediately upon their declaration with the help of a the following form:

type variable = value;

In this construct, a variable named variable of type type is initialized with value.

 

3. An example of initializing a single base type variable in a class

The class Month is given, which implements the month of the year. The class declares one hidden variable ‘month’, which is initialized to 5 immediately upon declaration.

// class that implements the month of the year
class Month
{
  // initialization of an internal variable when it is declared
  int month = 5;
  public int GetMonth() { return month; }
  public void SetMontgh(int _month) { month = _month; }
}

Using the object of class Month in other program code

Month mn = new Month();
int t = mn.GetMonth(); // t = 5

 

4. An example of initializing an array of variables of the base type in a class

Is demonstrated the initialization of an array of 5 double values, which is declared in the ArrayDouble5 class.

// class implements an array of 5 numbers of type double
class ArrayDouble5
{
  // array initialization when it is declared
  double[] A = { 3.5, 8.2, 1.6, 2.8, -0.0025 };

  // access methods
  // get an array element
  public double GetAi(int index)
  {
    if ((index >= 0) && (index < 5))
      return A[index];
    return 0.0;
  }

  // write new value to array item
  public void SetAi(int index, double value)
  {
    if ((index >= 0) && (index < 5))
      A[index] = value;
  }
}

Class usage may be as follows

// initialization the array in class
ArrayDouble5 ad = new ArrayDouble5();
double val = ad.GetAi(3); // val = 2.8
val = ad.GetAi(4); // val = -0.0025

 

5. Using an object’s initializer to initialize a class object in another class

The initialization of class objects using object initializers is demonstrated. Three classes are given: Line, Triangle, Figures. In the Line class, public variables are declared that describe the coordinates of a segment on a plane. In the Triangle class, public variables are declared that define the coordinates of the points of the triangle.

In the Figures class, two objects (instances) of the Line and Triangle classes are declared. In the Figures class, objects of the Line and Triangle classes are initialized using object initializers.

// class that implements the line on the coordinate plane
class Line
{
  public int x1, y1, x2, y2;
}

// class that implements a triangle on the coordinate plane
class Triangle
{
  public int x1, y1, x2, y2, x3, y3;
}

// class that implements a figure
class Figures
{
  // class object initialization
  Line ln = new Line { x1 = 0, y1 = 3, x2 = 2, y2 = 5 };
  Triangle tr = new Triangle { x1 = 1, y1 = 1, x2 = 4, y2 = 0, x3 = 2, y3 = 1 };

  // access methods
  public Line GetLine() { return ln; }
  public Triangle GetTriangle() { return tr; }
}

The use of class Figures

Figures fg = new Figures();
Line ln;
Triangle tr;
int t;

ln = fg.GetLine();
t = ln.x2; // t = 2
t = ln.y1; // t = 3

tr = fg.GetTriangle();
t = tr.y2; // t = 0
t = tr.x3; // t = 2

 

6. Using object initializer to initialize an array of objects in a class

The example demonstrates initialization of an array of Worker objects in the Workers class. Initialization is done using an object initializer.

// class describing a worker
class Worker
{
  // It is required with public access modifier
  public string name; // the name of worker
  public int age; // age
  public double salary; // a salary of worker
}

// class in which an array of 3 Worker objects is declared
class Workers
{
  public Worker[] wr = 
  {
    new Worker { name = "Filippov F.F.", age = 35, salary = 70320.55 },
    new Worker { name = "Johansonn S.", age = 37, salary = 66670.57 },
    new Worker { name = "Gustaffson G.G.", age = 69, salary = 129380.55 }
  };
}

Important: in order to be able to initialize the Worker[] array in the Workers class, it is necessary that the data of the Worker class be declared with the public access modifier.

Using an array of wr objects can be as follows:

Workers W = new Workers();
string name;
int age;
double salary;

name = W.wr[1].name; // name = Johansonn S.
age = W.wr[1].age; // age = 37
salary = W.wr[1].salary; // salary = 66670.57

 

7. Using object initializer to initialize a structure variable in a class

A Book structure that implements the book is declared. The CBook class demonstrates initialization of a structural variable of type Book. Initialization is possible only when a structural variable in a class is represented as a type-reference. This means that for a structured variable, memory is allocated by the operator new.

// structure that implements a book
struct Book
{
  public string title; // title of book
  public string author; // name of author
  public int year; // year of issue
  public float price; // book cost
}

class CBook
{
  // initialization of a structure variable in a class as a reference type
  public Book b = new Book { title = "Tell the time 5+", author = "H. Cather", year = 2017, price = 110.00f };
}

Using a CBook object can be as follows:

// the object of class CBook
CBook cb = new CBook();
string ttl = cb.b.title; // ttl = "Tell the time 5+"

Important: in order to be able to initialize the object b of type Book in the CBook class, the structure fields (title, author, year, price) must be declared as public.

 

8. An example of using an object initializer to initialize an array of structural variables

This example demonstrates how to declare and initialize an array of structures of type Book in the CBook class.

// structure implementing the book
struct Book
{
  public string title; // title of book
  public string author; // name of author
  public int year; // year of issue
  public float price; // book cost
}

class Books
{
  // initialization of an array of structural variables in a class
  public Book[] B =
  {
    new Book { title = "Computer coding for kids", author = "Carol Vorderman", year = 2015, price = 320.00f },
    new Book { title = "Math and English", author = "Paul Broadbent", year = 2015, price = 310.00f },
    new Book { title = "Spelling 5+", author = "Hannah Catner", year = 2017, price = 0.00f }
  };
}

Using the object of the class Books in other program code

// object of class Books
Books bk = new Books();
string author = bk.B[2].author; // author = "Hannah Catner"

 

9. An example of initializing a variable and an array of variables of type enumeration (enum)

A Months enumeration is specified that defines the months of the year. The example demonstrates:

  • initialization of a variable of type enumeration Months in the class CMonths. Three variables (class data members) are initialized with the names mn1, mn2, mn3;
  • initialization of an array of variables of type enumeration Months in the CMonths class.
// month of the year
enum Months
{
  Jan = 1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
}

// class in which internal variables of type 'enumeration' are initialized
class CMonths
{
  public Months mn1 = Months.Feb;
  public Months mn2 = Months.Jun;
  public Months mn3 = Months.Nov;

  // array of enumeration type variables
  Months[] array = { Months.Sep, Months.Jun, Months.Jan };
}

 

10. What requirements are imposed on the declaration of a class variable in the case of initialization of this variable by an object initializer?

To initialize a class variable using the object’s initializer, this variable must be declared as public with the ‘public’ access modifier. Otherwise, the compiler will generate the error message:

Variable is inaccessible due to its protection level

where variable – the name of the variable in the class to be initialized.


Related topics