C#-Classes

C# – What is OOP?

OOP means Object-Oriented Programming.

Writing methods or procedures that operate on data is what procedural programming entails, whereas object-oriented programming focuses on building objects that hold both data and methods.

Compared to procedural programming, object-oriented programming offers the following benefits:

  • OOP is simpler and faster to implement.
  • OOP gives the applications a distinct framework.
  • OOP facilitates the “Don’t Repeat Yourself” approach to C# code, making it simpler to maintain, alter, and debug.
  • With OOP, whole reusable applications may be developed more quickly and with less code.
Tip:The goal of the “Don’t Repeat Yourself” (DRY) principle is to minimize code repetition. Instead of repeating the codes, take the common ones for the program, put them in one location, and use them again.

C# – What are Classes and Objects?

The two primary components of object-oriented programming are classes and objects.

Examine the following example to understand the distinction between objects and classes:

class

Flowers

objects

Rose

Lilly

Mariglod

One more example:

class

Classroom

objects

Black board

Notebook

Chalk piece

 

 

In other words, an object is an instance of a class, and a class is a template for objects.

All of the class’s variables and methods are passed down to the individual objects upon creation.

The next chapter will cover a lot more information on classes and objects.

Classes and Objects

The last chapter introduced you to the object-oriented programming language, C#.

In C#, everything is connected to classes and objects, as well as their methods and attributes. For instance, an automobile is an object in the actual world. The car contains features like color and weight, as well as functions like brake and drive.

A class is a “blueprint” for building objects, similar to an object constructor.

Create a Class

Use the class keyword to create a class:

Create a class named “Car” with a variable color:

class Car

{

string color=”red”;

}

A variable is frequently referred to as a field (or attribute) when it is specified directly in a class.

While it’s not necessary, it’s a good idea to begin class names with an uppercase letter. Additionally, it is typical for the class name and the C# file to match, as this helps to organize our code. It is not necessary, though (as in Java).

Create an Object

A class is used to build an object. We can now use this to create objects because we have already constructed the Car class. Use the keyword new along with the class name and object name to create an object of class Car:

Example

To print the color value, create an object called “myObj” and utilize it as follows:
class Car
  {
    string color = “red”;
    static void Main(string[] args)
    {
      Car myObj = new Car();
      Console.WriteLine(myObj.color);
    }
Note that we use the dot notation (.) to access variables/fields inside a class (myObj.color). The following chapter will cover fields in more detail.

Multiple Objects

One class can have several objects created for it:

Example

Create two objects of Car:
  class Car
  {
    string color = “red”;
    static void Main(string[] args)
    {
      Car myObj1 = new Car();
      Car myObj2 = new Car();
      Console.WriteLine(myObj1.color);
      Console.WriteLine(myObj2.color);
    }
  }

Using Multiple Classes

Additionally, you can make a class object and use it in another class. This is frequently used to better organize classes (one class contains all of the fields and methods, and the other class contains the code to be performed, or the Main() method).
  • prog2.cs
  • prog.cs
prog2.cs class Car { public string color = “red”; }
 
prog.cs
  class Program
  {
    static void Main(string[] args)
    {
      Car myObj = new Car();
      Console.WriteLine(myObj.color);
    }
  }
Did you see the keyword that is public? It is called an access modifier, which says that the color variable/field of Car is accessible for other classes as well, such as Program. In the upcoming chapters, access modifiers and classes/objects will be covered in great detail.  

Class Members

“Class Members” is a term frequently used to describe fields and functions inside of classes:

Example

Make a Car class that consists of one method, two fields, and the class itself.
 // The class
{
class MyClass
    {
   // Class members
      string color = “red”; // field
          int maxSpeed = 200;// field
          public void fullThrottle( )//method
     Console.WriteLine(“The car is going as fast as it can!”);
      }
}

Fields

As you recall from the last chapter, variables within a class are referred to as fields, and you may access them by using the dot syntax (.) and by constructing an object of the class. The Car class object with the name myObj will be created in the example that follows. Next, we output the color and maxSpeed fields’ values:

Example

  class Car
  {
    string color = “red”;
    int maxSpeed = 200;
    static void Main(string[] args)
    {
      Car myObj = new Car();
      Console.WriteLine(myObj.color);
      Console.WriteLine(myObj.maxSpeed);
    }
  }
Additionally, you can change the fields after creating the object by leaving them blank:

Example

class Car
  {
    string color;
    int maxSpeed;
    static void Main(string[] args)
    {
      Car myObj = new Car();
      myObj.color = “red”;
      myObj.maxSpeed = 200;
      Console.WriteLine(myObj.color);
      Console.WriteLine(myObj.maxSpeed);
    }
  }
This is very helpful when making several objects of the same class:

Example

class Car
  {
    string model;
    string color;
    int year;
    static void Main(string[] args)
    {
      Car Ford = new Car();
      Ford.model = “Mustang”;
      Ford.color = “red”;
      Ford.year = 1969;
      Car Opel = new Car();
      Opel.model = “Astra”;
      Opel.color = “white”;
      Opel.year = 2005;
      Console.WriteLine(Ford.model);
      Console.WriteLine(Opel.model);
    }
  }

Object Methods

The C# Methods chapter taught you that methods are used to carry out certain tasks. Typically, methods are part of a class and specify the behavior of an object within that class. You can use the dot syntax to access methods, just like you do with fields. But keep in mind that the procedure needs to be made available to the public. And keep in mind that to call (run) the method, we need its name, two parentheses(), and a semicolon.

Example

  class Car
  {
    string color;                 // field
    int maxSpeed;                 // field
    public void fullThrottle()    // method
    {
      Console.WriteLine(“The car is going as fast as it can!”);
    }
    static void Main(string[] args)
    {
      Car myObj = new Car();
      myObj.fullThrottle();  // Call the method
    }
  }
Why did we specify the method as static, as in the C# Methods Chapter examples, yet public? The rationale is straightforward: public methods can only be accessed by objects, whereas static methods can be accessed without first constructing an instance of the class.  

Use Multiple Classes

As you may recall from the last chapter, we can use multiple classes—one for fields and methods, and another for execution—to achieve better structure. It is advised to do this:

prog2.cs

 class Car
{
     public string model;
     public string color;
      public int year;
     public void fullThrottle( )
     {
      Console.WriteLine(“The car is going as fast as it can!”);
      }
}

prog.cs

class Program
  {
    static void Main(string[] args)
    {
      Car Ford = new Car();
      Ford.model = “Mustang”;
      Ford.color = “red”;
      Ford.year = 1969;
      Car Opel = new Car();
      Opel.model = “Astra”;
      Opel.color = “white”;
      Opel.year = 2005;
      Console.WriteLine(Ford.model);
      Console.WriteLine(Opel.model);
    }
  }
The public keyword, also known as an access modifier, indicates that other classes, like Program, can also access the Car class’s fields.
A later chapter will have more information regarding Access Modifiers.
As you go on, you’ll discover additional information on constructors and properties, among other class members.

Constructors

An unique technique called a constructor is employed to initialize objects. A constructor’s benefit is that it gets invoked whenever a class object is created. It can be applied to initialize field values:

Example

create a constructor:
// Create a Car class
  class Car
  {
    public string model;  // Create a field
 
    // Create a class constructor for the Car class
    public Car()
    {
      model = “Mustang”; // Set the initial value for model
    }
 
    static void Main(string[] args)
    {
      Car Ford = new Car();  // Create an object of the Car Class (this will call the constructor)
      Console.WriteLine(Ford.model);  // Print the value of model
    }
  }
Keep in mind that the constructor name cannot have a return type (such as void or int) and that it must match the class name. Keep in mind that when an object is formed, the constructor is invoked. By default, constructors are included in all classes; if you don’t provide one for your class, C# does it for you. But then, you are unable to specify the fields’ initial values. Builders economize time! To truly grasp why, look at the last example on this page.

Constructor Parameters

Moreover, constructors can accept parameters, which is how fields are initialized. The constructor now has a string modelName parameter thanks to the example below. We set model to modelName (model=modelName) inside the constructor. The value of model is set to “Mustang” when we call the constructor and feed it a parameter (“Mustang“):

Example

 class Car
  {
    public string model;
    // Create a class constructor with a parameter
    public Car(string modelName)
    {
      model = modelName;
    }
    static void Main(string[] args)
    {
      Car Ford = new Car(“Mustang”);
      Console.WriteLine(Ford.model);
    }
  }
   //Output “Mustang”
As many parameters as you like are allowed:

Example

  class Car
  {
    public string model;
    public string color;
    public int year;
    // Create a class constructor with multiple parameters
    public Car(string modelName, string modelColor, int modelYear)
    {
      model = modelName;
      color = modelColor;
      year = modelYear;
    }
    static void Main(string[] args)
    {
      Car Ford = new Car(“Mustang”, “Red”, 1969);
      Console.WriteLine(Ford.color + ” ” + Ford.year + ” ” + Ford.model);
    }
  }
 //Outputs Red 1969 Mustang
 
Advice: Using an excessive amount of parameters in constructors can cause overloading, much like in other methods.

Constructors Save Time

Constructors are highly helpful since they assist reduce the amount of code, as seen by the example from the previous chapter:

Without Constructor:

prog.cs

  class Program
  {
    static void Main(string[] args)
    {
      Car Ford = new Car();
      Ford.model = “Mustang”;
      Ford.color = “red”;
      Ford.year = 1969;
      Car Opel = new Car();
      Opel.model = “Astra”;
      Opel.color = “white”;
      Opel.year = 2005;
      Console.WriteLine(Ford.model);
      Console.WriteLine(Opel.model);
    }
  }

With Constructor:

prog.cs

  class Program
  {
    static void Main(string[] args)
    {
      Car Ford = new Car(“Mustang”, “Red”, 1969);
      Car Opel = new Car(“Astra”, “White”, 2005);
 
      Console.WriteLine(Ford.model);
      Console.WriteLine(Opel.model);
    }
  }

Access Modifiers

You should be somewhat familiar with the public keyword by now, as it shows up in a lot of our examples:

public string color;

 

Access modifiers, such as the public keyword, are used to control the visibility and level of access to classes, fields, methods, and properties.

These are the access modifiers available in C#:

 
ModifierDescription
publicThe code is accessible for all classes
privateThe code is only accessible within the same class
protectedThe code is accessible within the same class, or in a class that is inherited from that class. You will learn more about inheritance in a later chapter
internalThe code is only accessible within its own assembly, but not from another assembly. You will learn more about this in a later chapter

Additionally, there are two combinations: private protected and protected internal.

Let us now concentrate on both public and private modifiers.

Private Modifier

A field that has been declared with a private access modifier can only be accessed by members of the same class:

Example

  class Car
  {
    private string model = “Mustang”;
 
    static void Main(string[] args)
    {
      Car myObj = new Car();
      Console.WriteLine(myObj.model);
    }
  }
 //Output will be “Mustang”
 
If you try to access it outside the class, an error will occur:

Example

  class Program
  {
    static void Main(string[] args)
    {
      Car myObj = new Car();
      Console.WriteLine(myObj.model);
    }
  }
// output  will be
‘Car.model’ is inaccessible due to its protection level
The field ‘Car.model’ is assigned but its value is never used
 

Public Modifier

A field that has been declared with a public access modifier is available to all classes:

Example

  class Program
  {
    static void Main(string[] args)
    {
      Car myObj = new Car();
      Console.WriteLine(myObj.model);
    }
  }
// output: Mustang

Why Access Modifiers?

to manage class member visibility (the security level of each class and class member separately).

To ensure that “sensitive” data is concealed from users, a process known as “encapsulation” must be completed. Fields are made private by declaring them as so. We’ll talk more about this in the upcoming chapter.

Note: If you omit to include an access modifier, all members of a class are private by default:

Example

class Car
{
   string model;    //private
   string year;       //private
}
Properties and Encapsulation
It is expected that you have a basic understanding of “Encapsulation” before we begin to explain attributes. Encapsulation is the process of ensuring that people cannot access “sensitive” data. To do this, you have to:
  • Declare variables and fields as private.
  •  Then, using properties, give the public get and set methods to access and update the value of a private field.

Properties

Private variables are only accessible within the same class; an outside class cannot access them, as you discovered in the last chapter. But occasionally, we must gain access to them, and attributes make this possible. A property has two methods: a set method and a get method. It functions similarly to a combination of a variable and a method.

Example

class Person
{
   private string name;  //field
   public  string Name  //property
   {
      get { return name; }  //get method
      set { name = value; } //set method
      }
 }

Example explained

The name field is connected to the Name property. Using the same name, but capitalizing the first letter, for both the property and the private field is a good practice. The value of the variable name is returned by the get method. The name variable is given a value by the set method. The value we provide the property is represented by the value keyword.
 
If you don’t fully understand it, take a look at the example below.
The Person class’s private field can now be accessed and updated via the Name property:

Example

class Person
{
   private string name;  //field
   public  string Name  //property
   {
      get { return name; }  //get method
      set { name = value; } //set method
      }
 }
  class Program
  {
    static void Main(string[] args)
    {
      Person myObj = new Person();
      myObj.Name = “Liam”;
      Console.WriteLine(myObj.Name);
    }
  }
    // Output: Liam

Automatic Properties (Short Hand)

Another method for using short-hand or automated properties in C# is to write get; and set; inside the property instead of defining the field for the property. The outcome of the next case will be the same as the previous one. The sole distinction is the reduced amount of code:

Example

Using automatic properties:

class Person
{
   private string name;  //field
   public  string Name  //property
   {
      get { return name; }  //get method
      set { name = value; } //set method
      }
 }
class Program
  {
    static void Main(string[] args)
    {
      Person myObj = new Person();
      myObj.Name = “Liam”;
      Console.WriteLine(myObj.Name);
    }
  }

Why Encapsulation?

  • Improved member control in the classroom (less chance that you or anybody else will make a coding error)
  • Write-only and read-only options are available for fields (assuming you use the set method exclusively).
  • Programmers can modify a single section of the code without affecting other sections, making it flexible.
  •  Enhanced data security

Inheritance (Derived and Base Class)

It is feasible for classes to inherit fields and methods from one another in C#. The “inheritance concept” is divided into two groups:
  • Derived class (child):The class that derives from another class.
  •  Base Class(parent): This is the class that one is inheriting from. 
Use the : sign to inherit from a class.
The Vehicle class (parent) in the example below provides the attributes and methods that the Car class (child) inherits:

Example

class Vehicle
  //base class (parent)
   public string brand = “Ford”;
    // Vehicle field
    //Vehicle method
       Console.WriteLine(“Tuut, tuut!”);
    }
}
class Car : Vehicle
   //derived class (child)
   public string modelName =”Mustang”;
  // Car field
 class Program
{
    static void Main(string[ ] args)
    {
    //Create a myCar object
   Car myCar = new Car();
 //Call the honk() method (From the Vehicle class) on the myCar object
  myCar.honk();
  //Display the value of the brand field (from the Vehicle class) and the value of the modelName from the Car class
  console.WriteLine(myCar.brand + ” ” + myCar.modelName);
   }
}
 
When And Why Should “Inheritance” Be Used?
Reusing fields and methods from an existing class when creating a new one is helpful for code reusability.
A hint: Also, check out Polymorphism, the following chapter, which employs inherited techniques to carry out various operations.

The sealed Keyword

Use the sealed keyword to prevent other classes from deriving from a class:

When attempting to access a sealed class, C# will produce the following error:
 sealed class Vehicle

    …

}

class Car  : Vehicle

{

   ….

}

The error message will be something like this:

‘Car’ : cannot derive from sealed type ‘Vehicle’