C#. An example of the development program, which is placed in different files




An example of the development program, which is placed in different files. Implementation of inheritance in classes. MS Visual Studio 2019 tools for splitting a program into parts


Contents


Search other websites:

Introduction

When creating class hierarchies containing large amounts of program code, it is advisable to implement each class in a separate file (module). Splitting large programs into separate parts (files) has the following advantages:

  • facilitates the perception of the overall structure of the program;
  • speeds up the search for the necessary code fragments;
  • reduces the number of subtle errors associated with a variety of codes concentrated in one file.

In this example, using the tools of Microsoft Visual Studio 2019, a program was developed whose code is divided into parts. Each part of the program is implemented in a separate file. For ease of use, a separate class is declared in each file. The name of each file matches the name of the class that is implemented in it.

The example demonstrates the implementation of 3 classes that interact with each other using the inheritance relationship (is-a relation).

 

Task

Implement a class hierarchy. The base class Human contains information:

  • name;
  • surname;
  • sex (male, female).

From the Human class, you need to inherit the Citizen class, which contains the following information:

  • passport number;
  • address of residence.

You must inherit the ForeignCitizen class from the Citizen class, which contains additional information:

  • foreign passport number;
  • visa opening date;
  • visa end date.

All classes must have the following elements:

  • constructor with parameters, initializing the fields of a particular class;
  • properties get/set for accessing class fields;
  • the Print() method, which displays information about the fields of the class on the screen.

Additional conditions:

  • classes must be in different modules. The Human class must be implemented in the module (file) “human.cs”, the Citizen class should be implemented in the “citizen.cs” module, the ForeignCitizen class should be implemented in the “foreignc.cs” module;
  • the ForeignCitizen class must be the last in the hierarchy and not support inheritance (sealed class).

 

Instructions

1. Creating a project using the Console Application template

After starting MS Visual Studio 2019, you need to create a new project. This is done in the standard way using a sequence of commands.

File->New->Project...

If Visual Studio 2019 has just started, the system will automatically open a corresponding window in which you can create a new project or select existing projects.

Using the window interface, you need to perform the following actions (Figure 1):

  • in the programming language selection element, select C#;
  • select Console App (.NET Core) in the list of templates;
  • to go further, select the Next button.

MS Visual Studio 2019. Window "Create a New Project"

Figure 1. Window “Create a New Project”. Creating a new project in MS Visual Studio 2019

After the completed actions, a new window “Configure your new project” will open (Figure 2). In this window you need to specify the name of the project, its location and the name of the solution.

In our case, the name DemoSplitFiles is set. Field “Location” and solution name can be left the default, which is installed by Visual Studio. After selecting the Create button, the system will generate a console application template.

MS Visual Studio 2019. Window "Configure your new project"

Figure 2. Window “Configure your new project”

 

2. Initial program configuration

At the moment, the program consists of one file Program.cs. In this file, the Program class is declared, which contains the entry point to the program – the static function Main().

At the moment, the text of the module Program.cs is as follows

using System;

namespace DemoSplitFiles
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Hello World!");
    }
  }
}

 

3. Adding the Human class and the Human.cs file

This clause details how to add a new file to a project. In accordance with the condition of the task, the class Human should be implemented in the file (module) human.cs.

The Visual Studio 2019 system (and other versions) is built in such a way that when you add a new class using the Visual Studio interface, this class will automatically be placed in a new file. You only need to specify the name of this file.

To add a new class to the project, in the main menu you need to call the sequence of commands

Project->Add Class...

as shown in Figure 3.

MS Visual Studio 2019. Command "Add Class...". Adding a new class to the project

Figure 3. Command “Add Class…”. Adding a new class to the project

This opens the “Add New Item – DemoSplitFiles” window, in which you need to do the following:

  • select “Visual C# Items” in the list of groups of installed items;
  • in the center of the window, select the Class element from the list of elements;
  • in the Name field set the name of file as the Human.cs;
  • after completing the settings, select the Add button.

MS Visual Studio - C#. Window "Add New Item". Specifying the file name for the class

Figure 4. Window “Add New Item”. Specifying the file name for the Human class

As a result of the actions performed, the Human class will be created, which is placed in the Human.cs file (Figure 5).

C# - Windows Forms. The program window with an active file

Figure 5. The program window with an active file Human.cs

As can be seen from Figure 5, at the moment the program consists of two files:

  • Human.cs – the file in which the Human class is located;
  • Program.cs is the file where the Program class is located.

Both classes are placed in the same namespace DemoSplitFiles.

The text of file human.cs is as follows

using System;
using System.Collections.Generic;
using System.Text;

namespace DemoSplitFiles
{
  class Human
  {
  }
}

 



4. Adding the Citizen class and citizen.cs file

At this point, add the Citizen class and the citizen.cs file. Adding the Citizen class follows the pattern of adding the Human class (see previous paragraph 2.3).

After the Citizen class is added, the text of the citizen.cs file will be as follows

using System;
using System.Collections.Generic;
using System.Text;

namespace DemoSplitFiles
{
  class Citizen
  {
  }
}

The Citizen class is declared in the DemoSplitFiles namespace, as are the previous Program and Human classes.

 

5. Adding ForeignCitizen class and ForeignCitizen.cs file

Following the pattern of previous classes Human, Citizen you need to add the ForeignCitizen class. After adding, the class is placed in a separate file ForeignCitizen.cs and contains the following code

using System;
using System.Collections.Generic;
using System.Text;

namespace DemoSplitFiles
{
  class ForeignCitizen
  {
  }
}

 

6. Program structure

At the moment, the program consists of 4 files:

  • Program.cs – contains the text of the Program class, in static function Main() is implemented. This function is the entry point to the program; it is executed first when the application starts;
  • Human.cs – contains the text of the Human class, which is the base for the Citizen and ForeignCitizen classes;
  • Citizen.cs – contains the text of the Citizen class, which is inherited from the Human class and is the base for the ForeignCitizen class;
  • ForeignCitizen.cs – contains the text of the ForeignCitizen class, which is inherited from the Citizen class.

 

7. The program code of class Human

In accordance with the condition of the problem, the Human class is basic in the class hierarchy. The text of the Human class is as follows:

using System;

namespace DemoSplitFiles
{
  // Class Human
  class Human
  {
    // 1. Internal fields of class
    protected string name;
    protected string surname;
    protected bool sex; // true - female, false - male

    // 2. Constructor with 3 parameters
    public Human(string _name, string _surname, bool _sex)
    {
      name = _name;
      surname = _surname;
      sex = _sex;
    }

    // 3. Properties to access internal class fields
    public string Name
    {
      get { return name; }
      set { name = value; }
    }

    public string Surname
    {
      get { return surname; }
      set { surname = value; }
    }

    public bool Sex
    {
      get { return sex; }
      set { sex = value; }
    }

    // 4. Method Print() - displays class field names on the screen
    public void Print()
    {
      Console.WriteLine("name: {0}", name);
      Console.WriteLine("surname: {0}", surname);
      if (sex)
        Console.WriteLine("sex: Female");
      else
        Console.WriteLine("sex: Male");
    }
  }
}

 

8. The program code of the class Citizen

The text of the Citizen.cs file is as follows

using System;

namespace DemoSplitFiles
{
  // Class Citizen - inherited from class Human
  class Citizen : Human
  {
    // 1. Internal class fields
    protected string password; // passport number
    protected string address;

    // 2. Class constructor
    public Citizen(string _name, string _surname, bool _sex,
        string _password, string _address) : base(_name, _surname, _sex)
    {
      password = _password;
      address = _address;
    }

    // 3. Properties to access the class fields
    public string Password
    {
      get { return password; }
      set { password = value; }
    }

    public string Address
    {
      get { return address; }
      set { address = value; }
    }

    // 4. Method that displays the values of class fields
    public new void Print()
    {
      base.Print(); // вызов метода базового класса
      Console.WriteLine("password: {0}", password);
      Console.WriteLine("address: {0}", address);
    }
  }
}

 

9. The program code of class ForeignCitizen

The text of the ForeignCitizen.cs file is as follows

using System;

namespace DemoSplitFiles
{
  // Class ForeignCitizen - inherited from class Citizen.
  // This class is sealed - cannot be inherited by another class.
  sealed class ForeignCitizen : Citizen
  {
    // 1. Internal class fields
    private string foreignPassport; // the number of foreign passport
    private DateTime visaOpen; // visa opening date
    private DateTime visaClose; // visa closing date

    // 2. Constructor - calls the base class constructor
    public ForeignCitizen(string _name, string _surname, bool _sex,
        string _password, string _address,
        string _foreignPassport, DateTime _visaOpen, DateTime _visaClose)
            : base(_name, _surname, _sex, _password, _address)
    {
      foreignPassport = _foreignPassport;
      visaOpen = _visaOpen;
      visaClose = _visaClose;
    }

    // 3. Properties to access the class fields
    public string ForeignPassport
    {
      get { return foreignPassport; }
      set { foreignPassport = value; }
    }

    public DateTime VisaOpen
    {
      get { return visaOpen; }
      set { visaOpen = value; }
    }

    public DateTime VisaClose
    {
      get { return visaClose; }
      set { visaClose = value; }
    }

    // 4. Method Print() - class fields output
    public new void Print()
    {
      base.Print(); // invoke the base class method
      Console.WriteLine("foreignPassport: {0}", foreignPassport);
      Console.WriteLine("visaOpen: {0}", visaOpen);
      Console.WriteLine("visaClose: {0}", visaClose);
    }
  }
}

 

10. The text of the Main() function. Testing the program

The Main() function is implemented in the Program class, which is declared in the Program.cs file. The Main() function demonstrates creating instances of developed classes implemented in other files. Since all classes are declared in the DemoSplitFiles namespace, you do not need to specify additional refinements or other actions to use the names of these classes. As this example shows, working with classes located in different MS Visual Studio – C# files is quite convenient.

The text of Program.cs file is as follows

using System;

namespace DemoSplitFiles
{
  class Program
  {
    static void Main(string[] args)
    {
      // 1. Using the instance of Human class
      Human hm = new Human("John", "Johnson", false);
      hm.Print();

      // 2. Using the instance of Citizen class
      Citizen ct = new Citizen("Petr", "Petrenko", false, "A101ksdl233", "New City");
      Console.WriteLine("------------------------");
      ct.Print(); // display the values of class fields

      // 3. Using the instance of ForeignCitizen class
      ForeignCitizen fc = new ForeignCitizen("Ivanov", "Ivan", false,
          "0230902ADK", "London", "023329032JJK",
          Convert.ToDateTime("02.02.2020"), Convert.ToDateTime("03.03.2085"));
          Console.WriteLine("------------------");
      fc.Print();
    }
  }
}

 

11. Program result
name: John
surname: Johnson
sex: Male
------------------------
name: Petr
surname: Petrenko
sex: Male
password: A101ksdl233
address: New City
------------------
name: Ivanov
surname: Ivan
sex: Male
password: 0230902ADK
address: London
foreignPassport: 023329032JJK
visaOpen: 2/2/2020 12:00:00 AM
visaClose: 3/3/2085 12:00:00 AM

 


Related topics