C# Programming Language Part 3 - OOPs


 C # OOPS (Object Oriented Programming)


C# OOPs stands for object Oriented Programming.

OOPs is about Creating Objects that contain both data and Methods.

Advantages of OOPs - 

Faster and Easier to execute

Provide a Clear structure of the Program

Oops keep the C# Code Easier to maintain, Modify and debug

 *  Abstraction *

In c#, Abstraction is a principle of object-oriented programming language (OOP), and it is used to hide the implementation details and display only essential features of the object.

 In Abstraction, by using access modifiers, we can hide the required details of the object and expose only necessary methods and properties through an object's reference.

 In real-time, the laptop is a perfect example of abstraction in c#. A laptop consists of many things such as a processor, RAM, motherboard, LCD screen, camera, USB ports, battery, speakers, etc. To use it, we need to know how to operate the laptop by switching it on, and we don’t need to know how internally all the parts are working. Here, the laptop is an object designed to expose only required features by hiding its implementation details.

 

In object-oriented programming, a class is the perfect example of abstraction. In c#, we can create a class with required methods, and properties and we can expose only necessary methods and properties using access modifiers based on our requirements.

public class Laptop
{
private string brand; 
 private string model;
 public string Brand
  {
  get { return brand; }
 set { brand = value; }
 }
   public string Model
 {
get { return model; }
  set { model = value; }
 }
   public void LaptopDetails()
  {
 Console.WriteLine("Brand: " + Brand);
  Console.WriteLine("Model: " + Model);
 }
   public void LaptopKeyboard()
  {
Console.WriteLine("Type using Keyword");
 }
private void MotherBoardInfo()
{
 Console.WriteLine("MotheBoard Information");
 }
   private void InternalProcessor()
 {
Console.WriteLine("Processor Information");
 }
}

Here, the public modifier allows defined fields, properties, and methods to access outside of the class. The private modifier is used to hide or restrict access to required fields, properties, and methods outside of class.

* Encapsulation *

In c#, Encapsulation is a process of binding the data members and member functions into a single unit. In c#, the class is the real-time example for encapsulation because it will combine various types of data members and member functions into a single unit.
 
Generally, in c# the encapsulation is used to prevent alteration of code (data) accidentally from the outside functions. In c#, by defining the class fields with properties, we can protect the data from accidental corruption.
 
If we define class fields with properties, then the encapsulated class won’t allow us to access the fields directly. Instead, we need to use getter and setter functions to read or write data based on our requirements.
 
Following is the example of defining an encapsulation class using properties with get and set accessors.
using System;
using System.Text;
namespace Tutlane
{
    class User
    {
       private string location;
       private string name;
       public string Location
       {  
          get
          {
             return location;
          }
          set
          {
             location = value;
          }
       }
       public string Name
       {
         get
         {
             return name;
         }
         set
         {
            name = value;
         }
       }
    }
    class Program
    {
       static void Main(string[] args)
       {
          User u = new User();
          // set accessor will invoke
          u.Name = "Suresh Dasari";
          // set accessor will invoke
          u.Location = "Hyderabad";
          // get accessor will invoke
          Console.WriteLine("Name: " + u.Name);
          // get accessor will invoke
          Console.WriteLine("Location: " + u.Location);
          Console.WriteLine("\nPress Enter Key to Exit..");
          Console.ReadLine();
       }
    }
}
If you observe the above example, we defined fields in encapsulated class using properties, and we are able to manipulate field values using get and set accessors of properties.

* Inheritance *

In c#, Inheritance is one of the primary concepts of object-oriented programming (OOP), and it is used to inherit the properties from one class (base) to another (child) class.
 
The inheritance will enable us to create a new class by inheriting the properties from other classes to reuse, extend, and modify other class members' behavior based on our requirements.
 
In C# inheritance, the class whose members are inherited is called a base (parent) class, and the class that inherits the members of the base (parent) class is called a derived (child) class.

using System;
namespace Tutlane
{
    public class A
    {
       public string Name;
       public void GetName()
       {
          Console.WriteLine("Name: {0}", Name);
       }
    }
    public class B: A
    {
       public string Location;
       public void GetLocation()
       {
          Console.WriteLine("Location: {0}", Location);
       }
    }
    public class C: B
    {
       public int Age;
       public void GetAge()
       {
          Console.WriteLine("Age: {0}", Age);
       }
    }
    class Program
    {
       static void Main(string[] args)
       {
          C c = new C();
          c.Name = "Suresh Dasari";
          c.Location = "Hyderabad";
          c.Age = 32;
          c.GetName();
          c.GetLocation();
          c.GetAge();
          Console.WriteLine("\nPress Any Key to Exit..");
          Console.ReadLine();
       }
    }
}
If you observe the above example, we implemented three classes (A, B, C), and class C is derived from class B, and class B is derived from class A.
 
By implementing a multi-level inheritance, class C can inherit the members declared in class B and class A.
 

* Polymorphism *

In c#, Polymorphism means providing an ability to take more than one form, and it’s one of the main pillar concepts of object-oriented programming after encapsulation and inheritance.
 
Generally, polymorphism is a combination of two words, poly, and another one is morphs. Here poly means “multiple” and morphs means “forms” so polymorphism means many forms.
 
In c#, polymorphism provides an ability for the classes to implement different methods called through the same name. It also provides an ability to invoke a derived class's methods through base class reference during runtime based on our requirements.
 
In c#, we have two different kinds of polymorphisms available, those are
 
  • Compile Time Polymorphism
  • Run Time Polymorphism
In c#, Compile Time Polymorphism means defining multiple methods with the same name but with different parameters. Using compile-time polymorphism, we can perform different tasks with the same method name by passing different parameters.
 
In c#, the compile-time polymorphism can be achieved by using method overloading, and it is also called early binding or static binding.
 
Following is the code snippet of implementing a method overloading to achieve compile-time polymorphism in c#.
 
using System;
namespace Tutlane
{
    public class Calculate
    {
       public void AddNumbers(int a, int b)
       {
          Console.WriteLine("a + b = {0}", a + b);
       }
       public void AddNumbers(int a, int b, int c)
       {
          Console.WriteLine("a + b + c = {0}", a + b + c);
       }
    }
    class Program
    {
       static void Main(string[] args)
       {
          Calculate c = new Calculate();
          c.AddNumbers(1, 2);
          c.AddNumbers(1, 2, 3);
          Console.WriteLine("\nPress Enter Key to Exit..");
          Console.ReadLine();
       }
    }
}
If you observe the above “Calculate” class, we defined two methods with the same name (AddNumbers), but with different input parameters to achieve method overloading, this is called a compile time polymorphism in c#.

    Run Time Polymorphism
In c#, Run Time Polymorphism means overriding a base class method in the derived class by creating a similar function. This can be achieved by using override & virtual keywords and the inheritance principle.
 
Using run-time polymorphism, we can override a base class method in the derived class by creating a method with the same name and parameters to perform a different task.
 
In c#, the run time polymorphism can be achieved by using method overriding, and it is also called late binding or dynamic binding.
 
Following is the code snippet of implementing a method overriding to achieve run time polymorphism in c#.
using System;
namespace Tutlane
{
    // Base Class
    public class BClass
    {
       public virtual void GetInfo()
       {
          Console.WriteLine("Learn C# Tutorial");
       }
    }
    // Derived Class
    public class DClass : BClass
    {
       public override void GetInfo()
       {
          Console.WriteLine("Welcome to Tutlane");
       }
    }
    class Program
    {
       static void Main(string[] args)
       {
          DClass d = new DClass();
          d.GetInfo();
          BClass b = new BClass();
          b.GetInfo();
          Console.WriteLine("\nPress Enter Key to Exit..");
          Console.ReadLine();
       }
    }
}
If you observe the above code snippet, we created two classes (“Users”, “Details”), and the derived class (Details) is inheriting the properties from the base class (Users). We are overriding the base class method GetInfo in the derived class by creating the same function to achieve method overriding; this is called a run time polymorphism in c#.
 
Here, we defined a GetInfo method with a virtual keyword in the base class to allow the derived class to override that method using the override keyword.
 
Only the methods with a virtual keyword in the base class are allowed to override in derived class using override keyword. To know more about it, check this Method Overriding in C#.

* Delegates *

In c#, the delegate is a type that defines a method signature, and it is useful to hold the reference of one or more methods which are having the same signatures.
 
By using delegates, you can invoke the methods and send methods as an argument to other methods.
 
In c#, the delegate is a reference type, and it’s type-safe and secure
In c#, the declaration of delegate will be same as method signature, but the only difference is we will use a delegate keyword to define delegates.
 
Following is the syntax of defining a delegate using delegate keyword in c# programming language.
 
<access_modifier> delegate <return_type> <delegate_name>()
Following is the example of declaring a delegate using delegate keyword in c#.
 
public delegate void UserDetails(string name);
using System;
namespace Tutlane
{
    // Declare Delegate
    public delegate void SampleDelegate(int a, int b);
    class MathOperations
    {
        public void Add(int a, int b)
        {
           Console.WriteLine("Add Result: {0}", a + b);
        }
        public void Subtract(int x, int y)
        {
           Console.WriteLine("Subtract Result: {0}", x - y);
        }
    }
    class Program
    {
       static void Main(string[] args)
       {
          Console.WriteLine("****Delegate Example****");
          MathOperations m = new MathOperations();
          // Instantiate delegate with add method
          SampleDelegate dlgt = m.Add;
          dlgt(10, 90);
          // Instantiate delegate with subtract method
          dlgt = m.Subtract;
          dlgt(10, 90);
          Console.ReadLine();
       }
    }
}
Types of Delegates in C#
In c#, we have two different types of delegates available. Those are
 
  • Single cast Delegates
  • Multicast Delegates
     Single Cast Delegates in C#
In c#, a delegate that points to a single method is called a single cast delegate, and it is used to hold the reference of a single method as explained in the above example.
     Multicast Delegates in C#
In c#, a delegate that points to multiple methods is called a multicast delegate, and it is used to hold the reference of multiple methods with a single delegate.
 
By using "+" operator, we can add the multiple method references to the delegate object. Same way, by using "-" operator we can remove the method references from the delegate object.
 
In c#, Multicast delegates will work with only the methods that are having void as return type. If we want to create a multicast delegate with the return type, then we will get a return type of the last method in the invoking list.
C# Delegates Overview
The following are the important properties of delegate in c# programming language.
 
  • We need to use a delegate keyword to define delegates.
  • In c#, delegates are used to hold the reference of one or more methods that have the same signature as delegates.
  • In c#, delegates are like function pointers in C++, but these are type-safe and secure.
  • By using delegates, you can pass methods as a parameter to the other methods.
  • In c#, we can invoke delegates as normal methods or by using Invoke property.
  • By using "+" operator, we can add multiple methods to delegates.
  • By using delegates, we can call multiple methods with a single event.

* C# Interface *

In c#, the interface is same as a class, but the only difference is class can contain both declarations and implementation of methods, properties, and events, but the interface will contain only the declarations of methods, properties, and events that a class or struct can implement.
 
An interface in c# is more like a contract,. The class or struct that implements an interface must provide an implementation for all the members specified in the interface definition.
 
Generally, c# will not support multiple inheritance of classes, but that can achieve by using an interface. Also, a structure in c# cannot be inherited from another structure or class, but that can inherit by using interfaces.
 
In c#, we can define an interface by using interface keyword.
In c#, a class can inherit only from one class, but we can implement multiple interfaces in a class or struct by using interfaces.
using System;
namespace Tutlane
{
    interface IName
    {
       void GetName(string x);
    }
    interface ILocation
    {
       void GetLocation(string x);
    }
    interface IAge
    {
       void GetAge(int x);
    }
    class User: IName, ILocation, IAge
    {
        public void GetName(string a)
        {
           Console.WriteLine("Name: {0}", a);
        }
        public void GetLocation(string a)
        {
           Console.WriteLine("Location: {0}", a);
        }
        public void GetAge(int a)
        {
           Console.WriteLine("Age: {0}", a);
        }
    }
    class Program
    {
       static void Main(string[] args)
       {
           User u = new User();
           u.GetName("Suresh Dasari");
           u.GetLocation("Hyderabad");
           u.GetAge(32);
           Console.WriteLine("\nPress Enter Key to Exit..");
           Console.ReadLine();
       }
    }
}

 

* Exception *

In c#, Exception is an unexpected event or an error that may occur during the execution of the program, and it will provide necessary information about the error which occurred in our application.
 
exceptions are generated by CLR (common language runtime) or application code. To handle runtime or unexpected errors in applications, c# has provided a built-in exception handling support by using try, catch, and finally blocks.
 
In c#, when an exception is thrown, the CLR (common language runtime) will look for the catch block that handles the exception. If the currently executing method does not contain such a catch block, then the CLR will display an unhandled exception message to the user and stops the program's execution.

As per the above syntax, the try block will contain the guarded code that may cause an exception so that if any errors occurred in our code, then immediately the code execution will move to catch block to handle those exceptions. In case, if no exception occurred in the try block, then the catch block will skip, and the execution will move to finally block.
To know more in detail about exception handling in c#, check the following exception handling topics.
 
  • try-catch
  • try-catch-finally
  • throw 

* Enum (Enumerator) *

In c#, enum is a keyword that is useful to declare an enumeration. In c#, the enumeration is a type that consists of a set of named constants as a list.
 
By using an enumeration, we can group constants that are logically related to each other. 
enum Week
{
   Sunday,
   Monday,
   Tuesday,
   Wednesday,
   Thursday,
   Friday,
   Saturday
}


* Collections *

In c#, the collection is a class that is useful to manage a group of objects in a flexible manner to perform various operations like insert, update, delete, get, etc., on the object items in a dynamic manner based on our requirements.
 
Generally, while working in c# applications, we will need to create or manage a group of related objects. In that case, we have two ways to create group objects in c#, i.e., using the arrays and collections.
 
In the previous section, we learned about arrays in c#, but those are useful only when working with a fixed number of strongly-typed objects. To solve this problem, Microsoft has introduced collections in c# to work with a group of objects that can grow or shrink dynamically based on our requirements.
 
In c#, the collection is a class. Hence, we need to declare an instance of the class before performing any operations like add, delete, etc., on the defined collection. The collections are implemented using the IEnumerable interface to access collection items by using a foreach loop.

C# Collection Types

In c#, we have a different type of collection classes are available; those are
 
  • Non-Generic (System.Collections)
  • Generic (System.Collections.Generic)
  • Concurrent (System.Collections.Concurrent)
  • C# Non-Generic Collections
In c#, non-generic collection classes are useful to store elements of different data types, and these are provided by System.Collections namespace. These collection classes are legacy types, so whenever possible, try to use generic collections (System.Collections.Generic) or concurrent collections (System.Collections.Concurrent).
 
Following are the different type of non-generic collection classes which are provided by System.Collections namespace.

C# Generic Collections
In c#, generic collections will enforce a type safety so we can store only the elements with the same data type, and these are provided by System.Collections.Generic namespace.
 
Following are the different type of generic collection classes which are provided by System.Collections.Generic namespace.

 
  Class       Description
ArrayList  - It is useful to represent an array of objects whose size is dynamically increased as required.
Queue  -     It is useful to represent a FIFO (First In, First Out) collection of objects.
Stack  -        It is useful to represent a LIFO (Last in, First Out) collection of objects.
Hashtable -  It is useful to represent a collection of key/value pairs organized based on the hash code of                        the key.

* Thread (Threading) *

In c#, the thread is a basic unit of execution within the process, and it is responsible for executing the application logic.
 
By default, every application or program will carry one thread to execute the application logic, and that thread is called the Main thread. So, we can say that every program or application is by default a single-threaded model.
 
For example, in a Windows operating system, if we open Microsoft Excel and Word applications simultaneously, then each application process will be taken care by separate threads.
 
In c#, we need to import System.Threading namespace in our program to work with threads. Once we import System.Threading namespace, we can create or access the threads using Thread class.
 
Generally, in c# when we start a program execution, the Main thread will automatically create to handle the program logic. If we create any other threads in our program by using Thread class those will become child threads for the Main thread.

No comments:

Post a Comment