C# Secure Programming

OOP’s

Object-oriented programming is the core ingredient of the .NET framework. OOP is so important that before embarking on the road to .NET, you must understand its basic principles and terminology to write even a simple program. The fundamental idea behind OOP is to combine into a single unit both data and the methods that operate on that data, with such units being called an object. All OOP languages provide mechanisms that help you implement the object-oriented model. They are encapsulation, inheritance, polymorphism, and reusability. Let’s take a brief look at these concepts:

Encapsulation

This mechanism binds together code and the data it manipulates and keeps both safes from outside interference and misuse. Encapsulation is a protective container that prevents code and data from being accessed by other code defined outside the container.

Inheritance

Inheritance is the process by which one object acquires the properties of another object. A type derives from a base type, taking all the base type members’ fields and functions. Inheritance is most useful when you need to add functionality to an existing type. For example, all .NET classes are inherited from System. Object classes, so a class scans its new functionality as well as the existing Object class functions and properties.

Polymorphism

Polymorphism is a feature that allows one interface to be used for a general class of action. This concept is often expressed as “one interface, multiple actions.” The specific action is determined by the exact nature of circumstances.

Reusability

Once a class has been written, created and debugged, it can be distributed to other programmers for use in their own program. This is called reusability or, in .NET terminology, this concept is called a component or DLL. However, in OOP, inheritance provides an important extension to the idea of reusability. A programmer can take an existing class and without modifying it, add more features to it.

Simple “Hello World” C# Program

This simple one class console “Hello world” program demonstrates many fundamental concepts throughout this article and several more later.

C# code

using System;
namespace oops
{
//class definition
public class SimpleHelloWorld
{
//Entry point of the program
static void Main(string[] args)
{
//<span class="hljs-built_in">print</span> Hello world”
Console.WriteLine(“Hello World!”);
}
}
}

SimpleHelloWorld is the name of the class that contains the Main () method. On line 1, a using directive signals the compiler that this source file refers to classes and constructs declared within the System namespace. At line 6, the public keyword indicates the program accessibility scope into other applications or components.

At line 7, there appears an opening curly brace ‘{‘which signals the beginning of the SimpleHelloWorld class body. Everything belongs to the class, like fields, properties, methods which appears in the class body between the opening and closing braces. The purpose of the Main () method is to provide an entry point for application execution.

The static keyword in the Main () method states that this method would be executed without instantiating the class.

Compiling the Program

You can compile a C# program into either assembly or module. If the program has one class that contains a Main () method, then it can be compiled directly into an assembly. This file will have a “.exe” extension. A program with no Main() method can be compiled into a module as follows:

csc /target:module “program name”

You can compile this program by pressing F9 or by simply running the C# command line compiler (csc.exe) against the source file as follows:

cscoops.cs

Classes and Objects

Classes are special kinds of templates from which you can create objects. Each object contains data and has methods to manipulate and access that data. The class defines what data and functionality each particular object of that class can contain.

A class declaration consists of a class header and body. The class header includes attributes, modifiers, and the class keyword. The class body encapsulates the members of the class, which are the data members and member functions. Here is the syntax of a class declaration:

Attributes accessibility modifiers class identifier: baselist { body }

Attributes provide additional context to a class like adjectives, for example, the Serializable attribute. Accessibility is the visibility of the class. The default accessibility of a class is internal. Private is the default accessibility of class members. The following table details the list of accessibility keywords:

KeywordDescription
publicPublic class is visible in the current and referencing assembly.
privateVisible inside current class.
protectedVisible inside current and derived class.
InternalVisible inside containing assembly.
Internal protectedVisible inside containing assembly and descendent of the current class.

Modifiers refine the declaration of a class. The list of all modifiers defined in the table is as follows:

ModifierDescription
sealedClass can’t be inherited by a derived class.
staticClass contains only static members.
unsafeThe class that has some unsafe construct likes pointers.
AbstractThe instance of the class is not created If the Class is abstract.

The base list is the inherited class. By default, classes inherit from a System. Object type. A class can inherit and implement multiple interfaces but cannot support multiple inheritances.

Step by Step Tutorial for Creating a Class

  • Open Visual Studio 2010 from the Start menu.
  • Go to File > New > Project, select Console Application in the right pane and give the project the name oops.
  • Then in the Solution Explorer, you will notice some files which are automatically created, such as:
  • You can also write your own code in the default created program.cs file but it is good programming practice to create a new class.
  • To add a new class, right-click the project name (oops) in the solution explorer, then click Add>Class. Name the class customer as follows:
  • When you open the customer.cs class, you will find default generated code:
    C# code
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
namespace oops
{
   class customer
   {
   }
}

Note: The C# console application project requires a single entry point Main () function which is already generated in the program class. For example, if you added a new customer class and wanted to define one more Main () entry point, then .NET throws an error of multiple entry points. So it is advisable to delete or exclude the program.cs file from the solution.

In this example, the customer class defines fields such as CustID, Name, and Address which you use to hold information about a particular customer. It might also define functionality that acts upon the data stored in these fields.

using System;
namespace oops
{
class customer
 {
// Member Variables
publicint CustID;
publicstring Name;
publicstring Address;
//constuctor <span class="hljs-keyword">for</span> initializing fields
 <span class="hljs-function"><span class="hljs-title">customer</span></span>()
 {
CustID=<span class="hljs-number">1101</span>;
 Name=<span class="hljs-string">"Tom"</span>;
 Address=<span class="hljs-string">"USA"</span>;
 }
//method <span class="hljs-keyword">for</span> displaying customer records (functionality)
public void <span class="hljs-function"><span class="hljs-title">displayData</span></span>()
 {
Console.WriteLine(<span class="hljs-string">"Customer="</span>+CustID);
Console.WriteLine(<span class="hljs-string">"Name="</span>+Name);
Console.WriteLine(<span class="hljs-string">"Address="</span>+Address);
 }
// Code <span class="hljs-keyword">for</span> entry point
 }
}

At line 9, we are defining a Constructor of the customer class for initializing the class member fields. The constructor is a special function that is automatically called when the customer class object is created (instantiated). At line 11, we are printing these fields to the console by creating a user-defined method displayData().

You can then instantiate an object of this class to represent one specific customer, set the field value for that instance and use its functionality as follows:

class customer
 {
// class members code
//Entry point
static void Main(string[] args)
 {
// object instantiation
 customer obj = new customer ();
//Method calling
obj.displayData();
//fields calling
Console.WriteLine(obj.CustID);
Console.WriteLine(obj.Name);
Console.WriteLine(obj.Address);
 }
 }

Image 1.1 Intellisense feature

Here you use the keyword new to declare the customer class instance. This keyword creates the object and initializes it. When you create an object of the customer class, .NET framework IDE provides you special features called Intellisense which provides access to all the class member fields and functions automatically. This feature is invoked when the “.” operator is put right after the object:

Normally, as the program size grows and complexities get higher in the code, the IntelliSense feature eases the programmer’s work by having records of all member fields, properties, and functions.

Multiple Class Declaration

Sometimes, circumstances require multiple classes to be declared into a single namespace. In that case, it is not mandatory to add a separate class into the solution; rather, you can attach the new class into the existing program.cs or to another one as follows:

using System;
namespace oops
{
classProgram
 {
public <span class="hljs-function"><span class="hljs-title">voidMainFunction</span></span>()
 {
Console.WriteLine(<span class="hljs-string">"Main class"</span>);
 }
static void Main(string[] args)
 {
//main class instance
Programobj = newProgram();
obj.MainFunction();

//other class instace
demodObj=new demo();
dObj.addition();
 }
 }

classdemo
 {
int x = <span class="hljs-number">10</span>;
int y = <span class="hljs-number">20</span>;
int z;

public void <span class="hljs-function"><span class="hljs-title">addition</span></span>()
 {
    z = x + y;
Console.WriteLine(<span class="hljs-string">"other class in Namespace"</span>);
Console.WriteLine(z);
   }
  }
}

Here in this example, we are creating an extra class demo inside the program.cs class at line 12 and finally, we are instantiating the demo class with program class inside the Main() entry at line 6 to 11. So it doesn’t matter how many classes we are defining into a single assembly.

Partial classes

Typically, a class will reside entirely in a single file. However, in situations where multiple developers need access to the same class, having the class in multiple files can be beneficial. The partial keywords allow a class to span multiple source files. When compiled, the elements of the partial types are combined into a single assembly.

Here are some rules to define a partial class:

  • All partial types must have the same accessibility.
  • Each partial type is preceded with the partial keyword.
  • If the partial type is sealed or abstract then the entire class will be sealed and abstract.
    In the following example, we are adding two classes, partialPart1.cs and partialPart2.cs, and declaring a partial class partialclassDemo in both classes.
partialPart1.cs
namespace oops
{
public partial class partialclassDemo
 {
public void <span class="hljs-function"><span class="hljs-title">method1</span></span>()
 {
Console.WriteLine(<span class="hljs-string">"method from part1 class"</span>);
  }
 }
}

**partialPart2.cs**

using System;
namespace oops
{
public partial class partialclassDemo
    {
public void <span class="hljs-function"><span class="hljs-title">method2</span></span>()
        {
Console.WriteLine(“method from part2 class”);
        }
    }
}

And finally, we are creating an instance of the partialclassDemo in the program.cs file as follows:

using System;
namespace oops
{
classProgram
    {
static void Main(string[] args)
        {
//partial class instance
partial class Demoobj = newpartialclassDemo();
            obj.method1();
            obj.method2();
        }
    }
}

Static classes

The static class is declared by using the static keyword. If the class is declared as static, then the compiler can never create an instance of the class. All the member fields, properties, and functions must be declared as static and they must access via class name directly, not by the class instance object.

using System;
namespace oops
{
static class staticDemo
    {
//static fields
staticint x = <span class="hljs-number">10</span>, y;
//static method
static void <span class="hljs-function"><span class="hljs-title">calcute</span></span>()
        {
            y = x * x;
            Console.WriteLine(y);
        }
static void Main(string[] args)
        {
          //<span class="hljs-keyword">function</span> calling directly
           staticDemo.calcute();
        }
    }
}

Creating and accessing Class Component Library

.NET provides you the capability of creating library (components) base applications rather than executables (“.exe”). Instead, the library project’s final build version will be as “.DLL” which can be a reference to other outside applications to expose its entire functionality.

Step by Step Tutorial

First, create a class library based application: Then, implement a math class library which is responsible for calculating square roots and the addition of two numbers:

using System;
namespaceLibraryUtil
{
publicclassMathLib
    {
<span class="hljs-function"><span class="hljs-title">publicMathLib</span></span>() { }
public void calculareSum(int x, int y)
        {
          int z = x + y;
          Console.WriteLine(z);
        }
public void calculareSqrt(double x)
        {
           double z = Math.Sqrt(x);
            Console.WriteLine(z);
        }
    }
}
  • Build this code and you will notice that a DLL file is created rather than an executable in the root directory of the application (path =D:\temp\LibraryUtil\LibraryUtil\bin\Debug\LibraryUtil.dll)
  • Now create another console based application where you utilize all the class library functionalities.
  • Then you have to add the class library DLL file reference to access the declared class in the library DLL. (Right click on the Reference > add reference > select path of DLLfile).
  • When you add the class library reference,you will notice in the solution explorer that a new LibraryUtil is added:
  • Now add the namespace of the class library file in the console application and create the instance of the class declared in the library:
using System;
usingLibraryUtil; // add library namespace
namespace oops
{
public class LibraryClass
    {
staticvoid <span class="hljs-function"><span class="hljs-title">Main</span></span>()
        {
//library class instance
MathLibobj = newMathLib();
//method populate
obj.calculareSum(<span class="hljs-number">2</span>, <span class="hljs-number">5</span>);
obj.calculareSqrt(<span class="hljs-number">25</span>);
        }
    }
}
  • Finally, run the application.

Constructor and Destructor

The constructor is a specialized function that is used to initialize the state of fields. The constructor has the same name as the class. Instance constructors are invoked with the new operator and can’t be called in the same manner as other member functions. Here are some important rules that pertains to constructor:

  • Classes with no constructor have an implicit constructor called default constructor, which is parameter-less. The default constructor assigns default values to fields.
  • Public constructor allows an object to be created in the current assembly or referencing assembly.
  • Only extern modifier is permitted to the constructor.
  • Constructor returns void but does not have an explicitly declared return type.
  • Constructor can have zero or more parameters.
  • Classes can have multiple constructors in the form of default, parameter or both.

The following example shows one constructor for the customer class.

using System;
namespace oops
{
class customer
    {
      // Member Variables
         publicstring Name;
         //constuctor <span class="hljs-keyword">for</span> initializing fields
          public customer(stringfname, stringlname)
        {
            Name= fname +” “+ lname;
        }
//method <span class="hljs-keyword">for</span> displaying customer records
public void <span class="hljs-function"><span class="hljs-title">AppendData</span></span>()
        {
          Console.WriteLine(Name);
        }
//Entry point
static void Main(string[] args)
        {
         // object instantiation
         customerobj = newcustomer(“Barack”, “Obama”);
        //Method calling
          obj.AppendData();
        }
    }
}

Note: The movement new statement is executed, and then the default constructor is called.

Static Constructor

The constructor can be static. You create a static constructor to initialize static fields. Static constructors are not called explicitly with the new statement, but when the class is first referenced. Here are some limitations of the static constructor:

  • Static constructors are parameter-less.
  • Static constructors can’t be overloaded.
  • Static constructors have no accessibility.

In the following example, customer class has a static constructor which initializes a static field and this constructor is called when the class is referenced in the Main () at line 26.

using System;
namespace oops
{
class customer
    {
      // Member Variables
      staticprivateint x;
     //constuctor <span class="hljs-keyword">for</span> static initializing fields
     static <span class="hljs-function"><span class="hljs-title">customer</span></span>()
        {
            x = <span class="hljs-number">10</span>;
        }
//method <span class="hljs-keyword">for</span> get  static field
<span class="hljs-function"><span class="hljs-title">staticpublicvoidgetData</span></span>()
        {
          Console.WriteLine(x);
        }
//Entry point
staticvoid Main(string[] args)
        {
         //static Method calling
          customer.getData();
        }
    }
}

Destructors

The purpose of the destructor method is to remove unused objects and resources. Destructors are not called directly in the source code but during garbage collection.

Garbage collection is nondeterministic. A destructor is invoked at an undermined movement. More precisely, a programmer can’t control its execution; rather, it is called by the Finalize () method. Like the constructor, the destructor has the same name as the class except a destructor is prefixed with a tilde (~). Here are some limitations of the destructor:

  • Destructors are parameter-less.
  • Destructor can’t be overloaded.
  • Destructors are not inherited.
  • Destructors can cause performance and efficiency implications.

The following implements a destructor and dispose of method. First of all, we are initializing the fields via the constructor, doing some calculation over that data and displaying it to the console. But at line 9, we are implementing a destructor which is calling a Dispose() method to release all of the resources.

using System;
namespace oops
{
classcustomer
    {
      // Member Variables
      publicint x, y;
     //constuctor <span class="hljs-keyword">for</span>  initializing fields
        <span class="hljs-function"><span class="hljs-title">customer</span></span>()
        {
          Console.WriteLine(“Fields inititalized”);
            x = <span class="hljs-number">10</span>;
        }

//method <span class="hljs-keyword">for</span> get field
<span class="hljs-function"><span class="hljs-title">publicvoidgetData</span></span>()
        {
            y = x * x;
           Console.WriteLine(y);
        }
//method to release resource explicitly
publicvoid <span class="hljs-function"><span class="hljs-title">Dispose</span></span>()
    {
        Console.WriteLine(“Fields cleaned”);
            x = <span class="hljs-number">0</span>;
            y = <span class="hljs-number">0</span>;
    }
//destructor
        ~<span class="hljs-function"><span class="hljs-title">customer</span></span>()
        {
            Dispose();
        }
//Entry point
staticvoid Main(string[] args)
        {
//instance created
customerobj = newcustomer();
obj.getData();
        }
    }
}

At line 12, when the instance is created, fields are initialized, but it is not necessary that at the same time the destructor is also called. Calling it is dependent on the garbage collector. If you want to see a destructor called into action, then put a breakpoint usingF9 at line 10 and then compile the application. CLR points its execution at the end of the program by highlighting line 10 in yellow color.

Function Overloading

Function overloading allows multiple implementations of the same functions in a class. Overloaded methods share the same name but have unique signatures. The number of parameters, type of parameters or both must be different. Functions can’t be overloaded on the basis of a different return type alone.

using System;
namespace oops
{
classfunOverload
    {
     publicstring name;
     //overloaded <span class="hljs-built_in">functions</span>
     publicvoidsetName(string last)
       {
            name = last;
        }
     public void <span class="hljs-built_in">set</span>Name(string first, string last)
        {
            name = first + “” + last;
        }
      public void <span class="hljs-built_in">set</span>Name(string first, string middle, string last)
        {
            name = first + “” + middle + “” + last;
        }
      //Entry point
      static void Main(string[] args)
        {
          funOverloadobj = newfunOverload();
          obj.setName(“barack”);
          obj.setName(“barack”,”obama”);
           obj.setName(“barack”,”hussian”,”obama”);
        }
    }
}

At line 3, 4, and 5, we are defining three same name methods but with different parameters. In the Main (), the movement creates an instance of the class and calls the functions setName() via obj at line 7,8, and 9, then Intellisense will show three signatures automatically.

Encapsulation

Encapsulation is the mechanism that binds together the code and the data it manipulates and keeps both safes from outside interference and misuse. In OOP’s, code and data may be combined in such a way that a self-contained box is created. When code and data are linked together in this way, an object is created and encapsulation is performed.

Within an object, code, data or both may be private or public to that object. Private code is known to and accessible only by another part of the object; that is, private code or data may not be accessible by a piece of the program that exists outside the object. When the code and data is public, other parts of your program may access it even though it is defined within an object.

using System;
namespace oops
{
classEncapsulation
    {
      ///<summary>
      /// Every member Variable and Function of the class are <span class="hljs-built_in">bind</span>
       /// with the Encapsulation class object only and safe with
       /// the outside inference
       ///</summary>
     // Encapsulation Begin
     int x;
     //class constructor
     public Encapsulation(intiX)
        {
          this.x = iX;
        }
       //calculating the square
       public void <span class="hljs-function"><span class="hljs-title">MySquare</span></span>()
        {
           intCalc = x * x;
           Console.WriteLine(Calc);
        }
        // End of Encapsulation
        //Entry point
      static void Main(string[] args)
        {
         //instance created
            customerobj = newcustomer(<span class="hljs-number">20</span>);
            obj.MySquare();
        }
    }
}

Inheritance

Inheritance is the process by which one object can acquire the properties of another object. Inheritance is a kind of relationship and it supports the concept of classification in which an object needs only define those qualities that make it unique within the class. Inheritance involves a base class and a derived class. The derived class inherits from the base class and can also override inherited members as well as add new members to extend the base class.

A base type represents the generalization, whereas a derived type represents a specialty. For instance, Employees can have the diverse type of such as hourly, salaried and temporary; so in that case, Employees is the general base class and hourly, salaried and temporary employee are specialized derived classes.

Classes can inherit from a single class and one or more interfaces. When inheriting from a class, the derived class inherits the members including the code of the base class. The important point to remember is that Constructors and Destructors are not inherited from the base class.

Here is the syntax of inheritance:

Class derivedClass :baseClass, Iterface1, Interface2 { body }

For example, we are defining two classes, Father and Child. You notice at line 7, we are implementing inheritance by using a colon (:). This movement means that all the properties that belong to the Father class are accessible to the Child class automatically.

using System;
namespace oops
{
//Base Class
publicclassFather
    {
     public void <span class="hljs-function"><span class="hljs-title">FatherMethod</span></span>()
        {
           Console.WriteLine(“this property belong to Father”);
        }
    }
//Derived class
public classChild : Father
    {
       <span class="hljs-function"><span class="hljs-title">publicvoidChildMethod</span></span>()
        {
          Console.WriteLine(“this property belong to Child”);
        }
    }
class Inheritance
    {
       //Entry point
       static void Main(string[] args)
        {
          FatherfObj = newFather();
          fObj.FatherMethod();
           //Here Child object can access both class methods
           ChildcObj = newChild();

           cObj.FatherMethod();

            cObj.ChildMethod();
        }
    }
}

At line 11, the Intellisense only shows the Father class functions but at line 15 to 16, the Child class object is able to access both class methods.


We can create a class in VB.net language or other .NET supported languages and can inherit them into C#.net class and vice versa. But a class developed in C++ or other unmanaged environments can’t be inherited into .NET.

Note: Cross language and multiple inheritance is not supported by .NET.

Accessibility

Accessibility sets the visibility of the member to the outside assembly or derived types. The following table describes member accessibility:

ModifiersOutside AssemblyDerived Class
privateNoNo
publicYesYes
protectedNoNo
internalYes ( this assembly only)Yes ( this assembly only)
internal protectedYes( this assembly only)Yes

Constructor in Inheritance

Constructors in a base class are not inherited in a derived class. A derived class has a base portion and a derived portion. The base portion initializes the base portion, and the constructor of the derived class initializes the derived portion.

Here is the syntax of constructor in inheritance:

Accessibility modifier classname(parameterlist1) : base(parameterlist2) { body }

So the base keyword refers to the base class constructor, while parameterlist2 determines which overloaded base class constructor is called.

In the following example, Child class constructor calls the one argument constructor of the base Father class.

using System;
namespace oops
{
//Base Class
public classFather
    {
//constructor
public <span class="hljs-function"><span class="hljs-title">Father</span></span>()
        {
           Console.WriteLine(“Father class constructor”);
        }
public void <span class="hljs-function"><span class="hljs-title">FatherMethod</span></span>()
        {
           Console.WriteLine(“this property belong to Father”);
        }
    }
//Derived class
public classChild : Father
    {
public Child()
            : <span class="hljs-function"><span class="hljs-title">base</span></span>()
        {
         Console.WriteLine(“child class constructor”);
        }
 public void <span class="hljs-function"><span class="hljs-title">ChildMethod</span></span>()
        {
        Console.WriteLine(“this property belong to Child”);

        }
    }
 class Inheritance
    {
       //Entry point
        static void Main(string[] args)
        {
        //Here Child object can access both class methods
ChildcObj = newChild();
cObj.FatherMethod();
cObj.ChildMethod();
Console.ReadKey();
        }
    }
}

At line 4, we are defining a base Father class constructor and in the derived class Child at line 8, we are initializing it explicitly via base keyword. If we pass any parameters in the base class constructor then we have to state them into the base block of the child class constructor.

Virtual Methods

By declaring a base class function as virtual, you allow the function to be overridden in any derived class. The idea behind the virtual function is to redefine the implementation of the base class method in the derived class according to our requirement. If a method is virtual in the base class, then we have to put the override keyword in the derived class. Neither member fields nor static functions can be declared as virtual.

using System;
namespace oops
{
class myBase
    {
   //virtual <span class="hljs-keyword">function</span>
    public virtual <span class="hljs-function"><span class="hljs-title">voidVirtualMethod</span></span>()
        {
        Console.WriteLine(“virtual method defined <span class="hljs-keyword">in</span> the base class”);
        }
    }
    class myDerived : myBase
    {
       // redefining the implementation of the base class method

       public override <span class="hljs-function"><span class="hljs-title">voidVirtualMethod</span></span>()
        {
         Console.WriteLine(“virtual method defined <span class="hljs-keyword">in</span> the Derive class”);
        }
    }
 class virtualClass
    {
      static void Main(string[] args)
        {
         // class instance
         newmyDerived().VirtualMethod();
          Console.ReadKey();
        }
    }
}

Hiding Methods

If a method with the same signature is declared in both base and derived classes, but the methods are not declared as virtual and override respectively, then the derived class version is said to hide the base class version. In most cases, you would want to override methods rather than hide them. Otherwise .NET automatically generates a warning.

In the following example, we are defining a VirutalMethod() in the myBase class but not overriding it in the derived class, so in that case, a compiler will generate a warning. The compiler will assume that you are hiding the base class method. To overcome this problem, if you prefix the new keyword in the derived class method, then the compiler will prefer the most derived version method. You can still access the base class method in the derived class by using the base keyword.

using System;
namespace oops
{
class myBase
    {
//virtual <span class="hljs-keyword">function</span>
    public virtual <span class="hljs-function"><span class="hljs-title">voidVirtualMethod</span></span>()
        {
         Console.WriteLine(“virtual method defined <span class="hljs-keyword">in</span> the base class”);
        }
    }
class myDerived : myBase
    {
        // hiding the implementation of base class method
      public new <span class="hljs-function"><span class="hljs-title">voidVirtualMethod</span></span>()
        {
      Console.WriteLine(“virtual method defined <span class="hljs-keyword">in</span> the Derive class”);
     //still access the base class method

base.VirtualMethod();
        }
    }
class virtualClass
    {
static void Main(string[] args)
        {
          // class instance

            newmyDerived().VirtualMethod();
            Console.ReadKey();
        }
    }
}

Abstract Classes

C# allows both classes and functions to be declared abstract by using the abstract keyword. You can’t create an instance of an abstract class. An abstract member has a signature but no function body and they must be overridden in any non-abstract derived class. Abstract classes exist primarily for inheritance. Member functions, properties, and indexers can be abstract. A class with one or more abstract members must be abstract as well. Static members can’t be abstract.

In this example, we are declaring an abstract class Employees with a method displayData() which does not have an implementation. Then we are implementing the displayData() body in the derived class. One point to be noted here: we have to prefix the abstract method with override keyword in the derived class.

using System;
namespace oops
{
//abstract class
public abstract classEmployess
    {
//abstract method with no implementation
public abstract void displayData();
    }
//derived class
public classtest : Employess
    {
//abstract class method implementation
public override void <span class="hljs-function"><span class="hljs-title">displayData</span></span>()
    {
    Console.WriteLine(“Abstract class method”);
    }
}
class abstractClass
    {
static void Main(string[] args)
    {
      // class instance
       newtest().displayData();
    }
}
}

Sealed Classes

Sealed classes are the reverse of abstract classes. While abstract classes are inherited and refined in the derived class, sealed classes cannot be inherited. You can create an instance of a sealed class. A sealed class is used to prevent further refinement through inheritance.

Suppose you are a developer of the class library and some of the classes in the class library are extensible but others are not; in that case, those classes are marked as sealed.

using System;
namespace oops
{
sealed class SealedClass
    {
      voidmyfunv();
    }
public class <span class="hljs-built_in">test</span> : SealedClass
//wrong. will give compilation error
    {
    }
}

Interface

An interface is a set of related functions that must be implemented in a derived class. Members of an interface are implicitly public and abstract. Interfaces are similar to abstract classes. First, both types must be inherited and second, you cannot create an instance of either. Although there are several differences, as follows:

  • An abstract class can contain some implementations but the interface cannot.
  • The interface can inherit only other interfaces but abstract classes can inherit from other classes and interfaces.
  • The abstract class can contain constructors and destructors but the interface cannot.
  • Abstract class contains fields but the interface cannot.

So the question is what to choose between these? Select interfaces because with the interface, the derived type can still inherit from other types and interfaces are more straightforward than abstract classes.

using System;
namespace oops
{
// interface
public interface xyz
    {
voidmethodA();
voidmethodB();
    }
// interface method implementation
class <span class="hljs-built_in">test</span> : xyz
    {
public void <span class="hljs-function"><span class="hljs-title">methodA</span></span>()
        {
          Console.WriteLine(“methodA”);
        }
public void <span class="hljs-function"><span class="hljs-title">methodB</span></span>()
        {
Console.WriteLine(“methodB”);
        }
    }
class interfaceDemo
    {
static void Main(string[] args)
        {
 testobj = newtest();
obj.methodA();
obj.methodB();
        }
    }
}

Interface can be inherited from other interfaces as follows:

public interface xyz
    {
voidmethodA();
voidmethodB();
    }
public interface abc : xyz
    {
     voidmethodC();
    }

Polymorphism

Polymorphism is the ability to treat different objects in the same manner. It is one of the significant benefits of inheritance. We can decide the correct call at run time based on the derived type of the base reference. This is called late binding.

In the following example, instead of having separate routines for hrDepart, itDepart, and financeDepart class, we can write a generic algorithm that uses the base type functions. The method LeaderName() declared in the base abstract class is redefined as per our needs in different-2 classes.

using System;
namespace oops
{
public abstract class Employee
    {
       public virtual void LeaderName()
        {
        }
    }
public class hrDepart : Employee
    {
      public override void LeaderName()
        {
          Console.WriteLine(“Mr. jone”);
        }
    }
public class itDepart : Employee
    {
    public override void LeaderName()
        {
          Console.WriteLine(“Mr. Tom”);
        }
    }
 public class financeDepart : Employee
    {
      public override void LeaderName()
        {
          Console.WriteLine(“Mr. Linus”);
        }
    }
class PolymorphismDemo
    {
     static void Main(string[] args)
        {
          hrDepart obj1 = newhrDepart();
          itDepart obj2 = newitDepart();

          financeDepart obj3 = newfinanceDepart();
            obj1.LeaderName();
            obj2.LeaderName();
            obj3.LeaderName();
               Console.ReadKey();
        }
    }
}