Monday, November 1, 2021

C# Class As a Type

Main points about class

  • Class is a template to create objects.
  • Class is user defined data type.
  • Class represents a business entity.
  • Class is composed of fields, properties and methods.
  • Fields of a class represent data of its objects.
  • Methods of a class represent behavior of its objects. 
  • Properties represent cross over between data and behavior of objects of a class.
  • Every class must have constructor(s) to create objects.

Introduction

C# is an object-oriented programming (OOP) language in which objects are the centerpiece of programming. In OOP, program is written around objects. The objects together determine the direction and result of the program.

In OOP, the object is the fundamental unit of program. Just as a building is made up of bricks, similarly, in object-oriented programming, object is the fundamental building block of the program. Just as there is a template or mould for making bricks inside a furnace, in the same way, object-oriented programming has templates for creating different type of objects, the template is called class in the OOP language.

We know about different built-in data types like Integer, String, Boolean etc. These different data types specify what type of data a variable will accept and what type of operation can be performed with the variable of a data type. Built-in data types are readymade types whereas a class is a customized type which is created by programmer to create objects according to specific requirement. C# provides facility to create class to build objects from it. A class is a template that contains fields to store data and set of methods which work upon fields of the class to provide operations of the class.

In other words, a class is a set of fields, properties and methods in which the fields are used to store the data of the object created by the class whereas the methods are used to manipulate the data by working on that data.

Once a class has been created by the programmer, many objects can be created based on that class. There are constructors within a class to construct objects. About the constructor we will study in separate post. The main function of the constructor is to initialize the values of the data of objects.

The purpose of programming is to solve a business problem. To solve the business problem, different types of business entities related to that business, also called business objects, have to be identified. After identifying the business entities, the attributes of the entities have to be outlined, which are related to the problem of that business. Classes are used to deal with such business entities. The attributes of business entity are represented as fields of the class. A special category of fields called Properties will be studied in separate post.

When we create RDBMS relational database model, we define database entities. Parallel analogy can be drawn in object oriented programming. In OOP, we have to determine business entities, the individual entities are called objects and entity set is called class.

Class has fields to represent characteristics of objects

For example, in a school management system, there are many types of entities such as teachers, students, staff, etc. There are many individual teachers in a school but all these teachers have some common characteristics such as name, age, qualification, salary, joining date etc. Based on these characteristics, we can represent teacher class. In following C# Teacher class, for simplicity, only fields of the class are given omitting the methods of the class. Note that no specific teacher's name, age, qualification etc. are given within the Teacher class.
public class Teacher
{
  int Id;
  string Name;
  int Age;
  string Qualification;
  string JoiningDate;
}

Some points about the syntax of class are as follows.

  • Class name is written in proper case after class keyword.
  • The access specifier of class can be public or internal.
  • For public class, we must explicitly use public keyword before class keyword.
  • For internal class, we may omit internal keyword before class keyword because by default class has internal access specifier.
  • Members of class are written inside opening and closing curly braces.

Class has methods to represent behavior of objects

The example of Teacher class shown above is incomplete because methods are omitted in it. Within a class there is not only data but also methods that operate on the data of that class. For example, if a teacher increases his/her qualification then his/her qualification should change. We will need a method to perform the task of updating the value of qualification. Remember that methods of a class determine the behavior of the class. In below example, Teacher class contains both fields and method.
public class Teacher
{
  int Id;
  string Name;
  int Age;
  string Qualification;
  string JoiningDate;
  
  public string UpdatedQualification( string newQualification )
  {
    // Logic to change Qualification 
Qualification = newQualification;
} }
We can also update the age of the Teacher. For this, we can add another method in Teacher class as shown below.
public class Teacher
{
  int Id;
  string Name;
  int Age;
  string Qualification;
  string JoiningDate;
  
  public string UpdatedQualification( string newQualification )
  {
    // Logic to change Qualification
Qualification = newQualification;
} public string UpdatedAge( string newAge ) { Age = newAge;
} }

Creating object from class

In the following example, we see how objects are created from class. First, we create Employee class and then we will create two instances of Employee.
public class Teacher
{
  string Name;
  public void GetName()
  {
   Console.WriteLine("Employee is " + this.Name);
  }
  public void SetName(string name)
  {
   this.Name = name;
  }
}
To create objects of Employee class, we use new operator as shown below.

    internal class Program
    {
        static void Main(string[] args)
        {
            Teacher teacher1 = new Teacher();
            teacher1.SetName("Ajeet");
            teacher1.GetName();
            Teacher teacher2 = new Teacher();
            teacher2.SetName("Rakesh");
            teacher2.GetName();
            Console.ReadKey();
        }
    }

Reference variable and object

The new operator is followed by constructor of the class to create an instance of class. As no constructor is defined for the Employee class, we use default parameterless constructor after new keyword. This will create an object of Employee class. This created instance of Employee class is assigned to a variable employee1 which is of Employee type. The LHS of assignment operator i.e. teacher1 represents reference variable which refers(points) to the created object. Thus the statement Teacher teacher1 = new Teacher(); can be divided into two parts. 
  1. The RHS of the statement represents the creation of object using new operator and constructor
  2. and the LHS represents the reference variable which points to the created object. 
Note that object is created in heap while reference variable is created on the stack.

Types of class

There are two types of classes based on the modifier used with a class. They are as follows.
  1. public class
  2. internal class
C# allows two types of modifiers with a type which can be either internal or public. As class is a type, so, a class can be public class or internal class in C#.  Public class is available to any project of the application. On the other hand, internal class is available only within the project in which it is defined.

Another way to classify a class is in terms of static and non static modifiers.
  1. Static class
  2. Non static class
Now we look at the difference between static class and non static class.

Static class

First of all we look at the important characteristics of static class in C#.
  • All the members of static class are static. It means that all the fields, properties and methods of static class are static.
  • As constructor is a special kind of method, so it is also static in a static class. 
  • There can be one and only one constructor in  static class.  
  • No modifier such as public, private, protected etc. can be used with static constructor in static class.
  • Static constructor is always paramterless. As static constructor is invoked before creation of any object, no parameter can be passed to it.
  • Static constructor is used to initialize the static fields of static class.
  • Static class can be public or internal.

Non static class

  • Unlike static class, a non static class have both - non and static members.
  • A non static class can have parameterized constructor which is not possible with static class.
  • A  non static class can have n numbers of constructors but static class can have one and only one constructor.
  • A non static class can be used to create distinct objects which is not possible with static class. A static class cannot create object.
  • A static constructor is always called before non static constructor. It means that static class is consumed before non static class.

No comments:

Post a Comment

Hot Topics