You are on page 1of 22

18MCA51 [Programming using C#] 2020 1

Encapsulation
Encapsulation is an object-oriented principle of hiding the internal state and behavior of an object, making
our code more maintainable. In other words, Encapsulation is a process of binding data members (variables,
properties) and member functions (methods) into a single unit”. And Class is the best example of
encapsulation. The concept of encapsulation revolves around the notion that an object’s internal data should
not be directly accessible from an object instance. Rather, if the caller wants to alter the state of an object, the
user does so indirectly using accessor (i.e. “getter”) and mutator (i.e. “setter”) methods.Abstraction and
encapsulation are related features in object oriented programming. Abstraction allows making relevant
information visible and encapsulation enables a programmer to implement the desired level of abstraction.

Important points
 Through encapsulation a class can hide the internal details of how an object does something.
Encapsulation solves the problem at the implementation level.
 A class or structure can specify how accessible each of its members (variables, properties, and
methods) is to code outside of the class or structure. Encapsulation simplifies the interaction between
objects. An object can use another object without knowing all its data or how its data is maintained.
For example, a Client object might have name, address, company, and department properties. If a
Bank object wants to use a Client object, it can request the name and address for the bank without
needing to know the company and department details of the Client object.
 With the help of encapsulation, a class can change the internal implementation without hurting the
overall functionality of the system.
 Encapsulation protects abstraction.

Need or purpose of encapsulation


 To hide and prevent code (data) from the outside world (i.e.other classes and assemblies).
 To prevent code (data) from accidental corruption due to programming errors so that we can deliver
expected output. Due to programming mistakes, code may not behave properly and it has an effect on
data and then it will affect the functionality of the system. With encapsulation we can make variables,
properties, and methods private so it is not accessible to all but accessible through proper channels
only to protect it from accidental corruption from other classes.
 To have a class better control over its fields (validating values etc…).

Encapsulation is implemented by using access specifiers. An access specifier defines the scope and
visibility of a class member. C# supports the following access specifiers:

Access Modifier Description (who can access)


private Only members within the same type. (default for type members)
protected Only derived types or members of the same type.
Only code within the same assembly. Can also be code external to object as long as it is
internal
in the same assembly? (default for types)
Either code from derived type or code in the same assembly. Combination of protected or
protected internal
internal.
public Any code. No inheritance, external type, or external assembly restrictions.

To illustrate the need for encapsulation services, assume we have created the following class definition:
// A class with a single public field.

Dept of MCA
18MCA51 [Programming using C#] 2020 2
class Book
{
public int numberOfPages;
}

The problem with public field data is that the items have no ability to intrinsically “under-stand” whether the
current value to which they are assigned is valid with regard to the current business rules of the system. As
we know, the upper range of a C# int is quite large (2,147,483,647). Therefore, the compiler allows the
following assignment:
static void Main(string[] args)
{
Book miniNovel = new Book();
miniNovel.numberOfPages = 30000000;
}

Although we have not overflowed the boundaries of an int data type, it should be clear that a mini-novel with
a page count of 30,000,000 pages is a bit unreasonable. As we can see, public fields do not provide a way to
trap logical upper (or lower) limits. If our current system has a business rule that states a book must be
between 1 and 1,000 pages, we are at a loss to enforce this programmatically. Because of this, public fields
typically have no place in a production-level class definition.
Encapsulation provides a way to preserve the integrity of an object’s state data. Rather than defining public
fields (which can easily foster data corruption), we should get in the habit of defining private data, which is
indirectly manipulated using one of two main techniques:
 Define a pair of accessor (get) and mutator (set) methods.
 Define a .NET property.

Whichever technique we choose, the point is that a well-encapsulated class should protect its data and hide
the details of how it operates from the prying eyes of the outside world. This is often termed black box
programming. The beauty of this approach is that an object is free to change how a given method is
implemented under the hood. It does this without breaking any existing code making use of it, provided that
the parameters and return values of the method remain constant.

Encapsulation using accessors and mutators 


We will start first by set the class variables as private then the object user cannot change or obtain the values
directly.
public class Employee
{
    private string Name;
    private int Age;
}
 
Employee firstEmp = new Employee();  //creating the object

//Compile time error


firstEmp.Name = "Amr!?Ashush";
firstEmp.Age = 50000; 
 
We will now add two methods one to get the value (Accessor) and the other to set the value (Mutator).

Dept of MCA
18MCA51 [Programming using C#] 2020 3
These methods will allow us to validate the values before the object user change or obtain the value.
Our employee class will be as follow:
public class Employee
{
    private string name;
    private int age;
 
    public int GetAge()     //Age Accessor
    { return age; }
   
    public void SetAge(int age) //Age Mutator
    {
         if(age > 60)
        {
             Consol.WriteLine("Employee age can not be more than 60");
        }
        else
        {
            this.age = age;
        }
    }
 
    public string GetName() //Name Accessor
    { return name; }
 
    public void SetName(string name) //Name Mutator
    {
        if (name.IndexOf('?') > 0)
        {
             Consol.WriteLine("Illegal Character can not be in the name");
        }
        else
        {
            this.name = name;
        }
    }
}

Now the object user must go through the accessor and mutator in order to change or obtain the value, so he
cannot set illegal value to the entity.
//creating the object
Employee firstEmp = new Employee(); 
firstEmp.SetName("Amr"); //use mutators (it's OK)
firstEmp.SetAge("23"); 
string EmployeeName = firstEmp.GetName(); //use accessors to get the values
int EmployeeAge = first Emp.GetAge(); 
firstEmp.SetName("Amr?"); //try to set illegal values (Error)
firstEmp.SetAge(100); 

Output:
Illegal Character can not be in the name 

Dept of MCA
18MCA51 [Programming using C#] 2020 4
Employee age can not be more than 60
 
Encapsulation using Properties
We can enforce encapsulation by using properties which allow you to access the data in the class.
A single property gives you the ability to set or obtain the value of a variable instead of using two different
methods as accessor and mutator. 
public class Employee
{
    private string name;
    private int age; 
    public string Name //the name property
    {
        Get //the accessor
 { return name; }
        set //the mutator
         { name = value; }
    }
}
Employee firstEmp = new Employee(); //creating the object
firstEmp.Name = "Amr"; //using the property to set value 
string n = firstEmp.Name; //using the property to get value
//the name property to validate
public string Name
{
    get{ return name; }
    set
    {
         if(name.IndexOf('?') > 0)
        {
             Consol.WriteLine("Illegal Character can not be in the name");
        }
        else
        {
            name = value;
        }
    }

Inheritance:
Inheritance is a powerful feature of Object Oriented Programming languages. One of the absolute key aspects
of Object Oriented Programming (OOP), which is the concept that C# is built upon, is inheritance.
Inheritance is the ability to create classes which inherits certain aspects from parent classes. The entire .NET
framework is built on this concept, with the "everything is an object" as a result of it. Even a simple number
is an instance of a class, which inherits from the System.Object class.
We can extend the functionality of an existing class by creating a new class that derives from the existing
class. The derived classinherits the properties of the base class, and we can add or override methods and
properties as required.In C#, both inheritance and interface implementation are defined by thecolon
(: operator). The base class should always be leftmost in the class declaration. The following code defines a
base class RentalItem and two derived classes DVD and Book that inherit the base class. 
public class RentalItem

Dept of MCA
18MCA51 [Programming using C#] 2020 5
{
        string _title;
        public string Title
        {
            get { return _title; }
            set { _title = value; }
        }
        public Boolean CheckStock(string title)
        {
                            return true; //code to check if in stock.returns true for demo.
        }
   }
   public class DVD : RentalItem
   {
   }
   public class Book : RentalItem
   {
   }
The derived classes inherit the base class's properties and methods and clients of the derived class have no
knowledge of the base class. The derived class is not limited to the properties and methods of the base class.
They can further define properties and methods as needed. The following code shows the derived class Book
defining its own property ISBN.
   public class Book : RentalItem
   {
       string _ISBN;
        public string ISBN
       {
           get { return _ISBN; }
           set { _ISBN = value; }
       }
   }
Clients of the Book class will be exposed to both properties Title and ISBN as shown in the following screen
shot.

There are many times when the derived class needs to use the functionality of the base class but also needs to
add some functionality unique to the derived class. In this case the derived DVD class uses the keyword base
to call the base class RentalItem's CheckStock method as shown in the following code.  

Dept of MCA
18MCA51 [Programming using C#] 2020 6
public class DVD : RentalItem
   {
       public Boolean Rent(string title, int age)
       {
           if(base.CheckStock(title))
           {
               //code to check rating against age of renter. returns true for demo
               return true;
           }
           else
           {
               return false;
           }
       }
   }

Methods inherited by the derived class can be overloaded just as you would overload any method in the same
class. The method names are the same but the method signatures are different. The following code shows the
Book class overloading the CheckStock method of the RentalItem base class.  
public class Book : RentalItem
   {
       string _ISBN;
       public string ISBN
       {
           get { return _ISBN; }
           set { _ISBN = value; }
       }
       public Boolean CheckStock(string title, string author)
       {           //code to check if in stock.returns true for demo.
           return true;
       }
   }
A method of the derived class can override a method of the base class using the override key word. For
example the Book class can override the CheckStock method of the RentalItem base class to pass in the
ISBN instead of the title.       
public override Boolean CheckStock(string ISBN)
       {
           //code to check if in stock.returns true for demo.
           return true;
       }
In this case clients of the Book class could use the overridden method and would not see the RentalItem's
method.

Inheritance and Constructors


Base class objects are always constructed before any deriving class. Thus the constructor for the base class is
executed before the constructor of the derived class. If the base class has more than one constructor, the

Dept of MCA
18MCA51 [Programming using C#] 2020 7
derived class can decide the constructor to be called. For example, we can define CoOrds class to add a two
constructor, as follows:
public class CoOrds
{
private int x, y;
public CoOrds()
{
x = 0;
y = 0;
}
public CoOrds(int x, int y)
{
this.x = x;
this.y = y;
}
}

Wecan then change the ColorCoOrds class to use a particular one of the available constructors using the base
keyword:

public class ColorCoOrds : CoOrds


{
public System.Drawing.Color color;
public ColorCoOrds() : base ()
{
color = System.Drawing.Color.Red;
}
public ColorCoOrds(int x, int y) : base (x, y)
{
color = System.Drawing.Color.Red;
}
}

Sealed Classes
Sealed class is used to define the inheritance level of a class. The sealed modifier is used to prevent
derivation from a class. An error occurs if a sealed class is specified as the base class of another class.
 A class, which restricts inheritance for security reason is declared, sealed class.
 Sealed class is the last class in the hierarchy.
 Sealed class can be a derived class but can't be a base class.
 A sealed class cannot also be an abstract class. Because abstract class has to provide functionality and
here we are restricting it to inherit. 
namespace sealed_class
{
    class Program
    {
        public sealed class BaseClass
        {
            public void Display()

Dept of MCA
18MCA51 [Programming using C#] 2020 8

        {
            Console.WriteLine("This is a sealed class which can;t be further inherited");
        }
    } 
        public class Derived : BaseClass
        {
            // this Derived class can;t inherit BaseClass because it is sealed
        }
        static void Main(string[] args)
        {
            BaseClass obj = new BaseClass();
            obj.Display();
            Console.ReadLine();
        }
    }
}
 
Sealed Methods
Sealed method is used to define the overriding level of a virtual method.Sealed keyword is always used with
override keyword.  
namespace sealed_method
{
    class Program
    {
        public class BaseClass
        {
           
            public virtual void Display()
            {
                Console.WriteLine("Virtual method");
            }
        }
        public class DerivedClass : BaseClass
        {
            // Now the display method have been sealed and can;t be overridden
            public override sealed void Display()
            {
                Console.WriteLine("Sealed method");
            }
        } 
       //public class ThirdClass : DerivedClass
       //{
        //    public override void Display()
       //    {

Dept of MCA
18MCA51 [Programming using C#] 2020 9

       //        Console.WriteLine("Here we try again to override display method which is not possible and will
give error");
       //    }
       //}
        static void Main(string[] args)
        {
            DerivedClass ob1 = new DerivedClass();
            ob1.Display();
 
            Console.ReadLine();
        }
    }
}
 
Extension methods
Extension methods are a new feature in C# 3.0. Extension methods enable to "add" methods to existing types
without creating a new derived type, recompiling, or otherwise modifying the original type. Extension
methods are a special kind of static method, but they are called as if they were instance methods on the
extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling
an extension method and the methods that are actually defined in a type.
The following list contains basic features and properties of extension methods:
1. It is a static method.
2. It must be located in a static class.
3. It uses the "this" keyword as the first parameter with a type in .NET and this method will be called by
a given type instance on the client side.
4. It also shown by Visual Studio intellisense. When we press the dot (.) after a type instance, then it
comes in VS intellisense.
5. An extension method should be in the same namespace as it is used or we need to import the
namespace of the class by a using statement.
6. We can give any name for the class that has an extension method but the class should be static.
7. If need to add new methods to a type and we don't have the source code for it, then the solution is to
use and implement extension methods of that type.
8. If we create extension methods that have the same signature methods as the type we are extending,
then the extension methods will never be called.

Dept of MCA
18MCA51 [Programming using C#] 2020 10

Polymorphism
Polymorphism is a Greek word that means "many-shaped" or “many forms”. Polymorphism is one of the
fundamental concepts of OOP. Polymorphism allows us to invoke derived class methods through a base class
reference during run-time. This is handy when we need to assign a group of objects to an array and then
invoke each of their methods. They won't necessarily have to be the same object type. However, if they're
related by inheritance, you can add them to the array as the inherited type. Then if they all share the same
method name, that method of each object can be invoked. 

Polymorphism provides following features: 


 It allows us to invoke methods of derived class through base class reference during runtime.
 It has the ability for classes to provide different implementations of methods that are called through
the same name.

Polymorphism can be achieved in two ways: 

1. Static or Compile time polymorphism/Overloading


2. Dynamic or Runtime polymorphism/Overriding

Compile time Polymorphism/Overloading


Compile time polymorphism is method and operators overloading. It is also called early binding.

Method Overloading

Method overloading is a concept where a class can have more than one method with the same name and
different parameters.Compiler checks the type and number of parameters passed on to the method and
decides which method to call at compile time and it will give an error if there are no methods that match the
method signature of the method that is called at compile time.Method overloading has nothing to do with
inheritance or virtual methods.If we use overload for method, there are couple of restrictions that the
compiler imposes.
 The rule is that overloads must be different in their signature, which means the name and the number
and type of parameters.
 Overloading is not possible on the basis of return type i.e. here cannot be two or more functions with
the same name and different return types within a single class.

Dept of MCA
18MCA51 [Programming using C#] 2020 11
 There is no limit to how many overload of a method we can have. We simply declare them in a class,
just as if they were different methods that happened to have the same name.

Example of Method Overloading (Compile Time Polymorphism)


 
using System;
 
namespace method_overloading
{
    class Program
    {
        public class Print
        {
           
            public void display(string name)
            {
                Console.WriteLine("Your name is : " + name);
            }
 
            public void display(int age, float marks)
            {
                Console.WriteLine("Your age is : " + age);
                Console.WriteLine("Your marks are :" + marks);
            }
        }
       
        static void Main(string[] args)
        {
 
            Print obj = new Print();
            obj.display("XYZ");
            obj.display(34, 76.50f);
            Console.ReadLine();
        }
    }
}
 
In the above code we can observe display method is called two times. Display method will work according to
the number of parameters and type of parameters.We use method overloading in situation where we want a
class to be able to do something, but there is more than one possibility for what information is supplied to the
method that carries out the task. 
 
Method Overloading showing many forms.
using System;
 
namespace method_overloading_polymorphism
{
    class Program
    {
        public class Shape

Dept of MCA
18MCA51 [Programming using C#] 2020 12
        {
            public void Area(float r)
            {
                float a = (float)3.14 * r;
                // here we have used funtion overload with 1 parameter.
                Console.WriteLine("Area of a circle: {0}",a);
            }
 
            public void Area(float l, float b)
            {
                float x = (float)l* b;
                // here we have used funtion overload with 2 parameters.
                Console.WriteLine("Area of a rectangle: {0}",x);
             } 
            public void Area(float a, float b, float c)
            {
                float s = (float)(a*b*c)/2;
                // here we have used funtion overload with 3 parameters.
                Console.WriteLine("Area of a circle: {0}", s);
            }
        } 
        static void Main(string[] args)
        {
            Shape ob = new Shape();
            ob.Area(2.0f);
            ob.Area(20.0f,30.0f);
            ob.Area(2.0f,3.0f,4.0f);
            Console.ReadLine();
        }
    }
}
  

Dept of MCA
18MCA51 [Programming using C#] 2020 13

Operator Overloading
Operator overloading which is also known as overloading basically provides a way to define and use
operators such as +, -, and / for user-defined classes or structs. It also allows us to define/redefine the way
operators work with our classes and structs. In this way, this technique allows programmers to make their
custom types look and feel like simple types such as int and string. It basically consists of nothing more than
a method declared by the keyword operator and followed by an operator. Operator method must be static.
Syntax<access-modifier >static<return-type>operator<operator>(Parameter list>
But not all operators of each type can be overloaded. Table -1 outlines the “overloadability” of the core
operators.

Overloading Binary Operators


To illustrate the process of overloading binary operators, we take the following simple Point structure:
namespace OperatorTest
{
// Just a simple everyday C# struct.
public struct Point
{
private int x, y;
public Point(int xPos, int yPos)
{
x = xPos;
y = yPos;
}
public override string ToString()
{
return string.Format("[{0}, {1}]", this.x, this.y);
}
public static Point operator + (Point p1, Point p2)// overloaded operator +
{
return new Point(p1.x + p2.x, p1.y + p2.y);
}

Dept of MCA
18MCA51 [Programming using C#] 2020 14
public static Point operator - (Point p1, Point p2)// overloaded operator -
{
return new Point(p1.x - p2.x, p1.y - p2.y);
}
}
class Prgram
{// Adding and subtracting two points.
public static void Main(string[] args)
{
Console.WriteLine("***** Fun with Overloaded Operators *****\n");
// Make two points.
Point ptOne = new Point(100, 100);
Point ptTwo = new Point(40, 40);
Console.WriteLine("ptOne = {0}", ptOne);
Console.WriteLine("ptTwo = {0}", ptTwo);
// Add the points to make a bigger point?
Console.WriteLine("ptOne + ptTwo: {0} ", ptOne + ptTwo);
// Subtract the points to make a smaller point?
Console.WriteLine("ptOne - ptTwo: {0} ", ptOne - ptTwo);
Console.ReadLine();
}
}
}
And what of the += and –+ Operators?
The shorthand assignmentoperators are automatically simulated if a type overloads the related binary
operator. Overloading binary operators results in a freebie shorthand operator. Thus, given thatthe Point
structure has already overloaded the + and - operators, we can write the following:
Console.WriteLine("ptThree += ptTwo: {0}", ptThree += ptTwo);
Console.WriteLine("ptFour -= ptThree: {0}", ptFour -= ptThree);

Overloading Unary Operators


C# also allows to overload various unary operators, such as ++ and --. When we overloada unary operator,
will also define a static method via the operator keyword; however in this case will simply pass in a single
parameter that is the same type as the defining class/structure. Forexample, we may update the Point with
the following overloaded operators:
public struct Point
{
...
// Add 1 to the incoming Point.
public static Point operator ++(Point p1)
{ return new Point(p1.x+1, p1.y+1); }
// Subtract 1 from the incoming Point.
public static Point operator --(Point p1)
{ return new Point(p1.x-1, p1.y-1); }
}
static void Main(string[] args)
{
...
// Applying the ++ and -- unary operators to a Point.
Console.WriteLine("++ptFive = {0}", ++ptFive);

Dept of MCA
18MCA51 [Programming using C#] 2020 15
Console.WriteLine("--ptFive = {0}", --ptFive);
}

Note: We can also overload Equality and comparison operators

Runtime Polymorphism/ Overriding


Runtime time polymorphism is done using inheritance and virtual/abstract functions. Method overriding is
called runtime polymorphism. It is also called late binding. When overriding a method; we change the
behavior of the method for the derived class. Overriding a method simply involves having another method
with the same prototype. 

Virtual method
A virtual method is a method that can be redefined in derived classes. A virtual method has an
implementation in a base class as well as derived the class. It is used when a method's basic functionality is
the same but sometimes more functionality is needed in the derived class. A virtual method is created in the
base class that can be overridden in the derived class. We create a virtual method in the base class using the
virtual keyword and that method is overridden in the derived class using the override keyword.
When a method is declared as a virtual method in a base class then that method can be defined in a base class
and it is optional for the derived class to override that method. The overriding method also provides more
than one form for a method. Hence it is also an example for polymorphism.

namespace VirtualExample
{   
    class Shape
    {   
       public double length=0.0;
       public double width =0.0;
       public double radius =0.0; 
       public Shape(double length, double width)
       {
           this.length = length;
           this.width = width;          
       }
       public Shape(double radius)
       {
           this.radius = radius;
       }
       public  virtual void Area()
       {          
           double area = 0.0;
           area = Math.PI * Math.Pow(radius, 2);
           Console.WriteLine("Area of Shape is :{0:0.00} ", area);
       }
    } 
    class Rectangle  : Shape
  {
        public Rectangle(double length, double width): base(length, width)

Dept of MCA
18MCA51 [Programming using C#] 2020 16
    {
        }    
        public override void Area()
    {
            double area = 0.0;
            area = length * width;
            Console.WriteLine("Area of Rectangle is :{0:0.00} ", area);
    }
  }
     class Circle : Shape
  {
        public Circle(double radius) : base(radius)
    {
    }
    }  
    class Program
  {
        static void Main(string[] args)
    {
             double length,width,radius=0.0;
             Console.WriteLine("Enter the Length");
             length = Double.Parse(Console.ReadLine());
             Console.WriteLine("Enter the Width");
             width = Double.Parse(Console.ReadLine());
             Rectangle objRectangle = new Rectangle(length, width);
              objRectangle.Area();
             Console.WriteLine("Enter the Radius");
             radius = Double.Parse(Console.ReadLine());
             Circle objCircle = new Circle(radius);
             objCircle.Area();
            Console.Read();
        }       
  }
}

Abstract classes and Abstract methods


Abstract classes are one of the essential behaviors provided by .NET. Commonly, we would like to make
classes that only represent base classes, and don’t want anyone to create objects of these class types. We can
make use of abstract classes to implement such functionality in C# using the modifier 'abstract'. Abstract
classes are not instantiated directly. An abstract class can also contain methods with complete
implementation, besides abstract methods. An abstract classmust contain at least one abstract method.
Abstract classes are useful when creating hierarchies of classes that model reality because they make it
possible to specify an invariant level of functionality in some methods, but leave the implementation of other
methods until a specific implementation of that class (a derived class) is needed. Following are the main
features of abstract class:
1. An abstract class can inherit from a class and one or more interfaces.
2. An abstract class can implement code with non-Abstract methods.
3. Abstract class can have modifiers for methods, properties etc.,

Dept of MCA
18MCA51 [Programming using C#] 2020 17
4. Abstract class can have constant and fields.
5. An abstract class can implement a property.
6. An abstract class can have constructors or destructors.
7. An abstract class cannot be inherited from by structures.
8. An abstract class cannot support multiple inheritance.

Abstract methods
Abstract methods are methods, which doesn’t contain and implementation. We define abstract methods
method using modifier ‘abstract’. When a method is declared as abstract in the base class then every
derived class of that class must provide its own definition for that method. It is mandatory to override
abstract method in the derived class. The abstract method in the derived class should be implemented with
the same access modifier, number and type of argument, and with the same return type as that of the base
class. Objects of abstract class type cannot be created, because the code to instantiate an object of the abstract
class type will result in a compilation error.

class Hello
{
public abstract class Talk
{
public abstract void speak();

}
public class SayHello : Talk
{
public override void speak()
{
Console.WriteLine("Hello!");
}
}
static void Main()
{
SayHello hello = new SayHello();

hello.speak();
}
}

Interfaces
An interface is nothing more than a named collection of semantically related abstract members. Interfaces
define properties, methods, and events, which are the members of the interface. Interfaces contain only the
declaration of the members. It is the responsibility of the deriving class to define the members. It often helps
in providing a standard structure that the deriving classes would follow.Interfaces can contain methods,
properties, events, indexers, or any combination of those four member types. An interface can't contain
constants, fields, operators, instance constructors, destructors, or types. Interface members are
automatically public, and they can't include any access modifiers. Members also can't be static.

Dept of MCA
18MCA51 [Programming using C#] 2020 18
Syntax of Interfaces

At a syntactic level, an interface is defined using the C# interface keyword. Unlike other .NET types,
interfaces never specify a base class (not even System.Object) and contain members that do not take an
access modifier (as all interface members are implicitly public). For example:
interface IEquatable<T>
{
bool Equals(T obj);
}

Any class or struct that implements the IEquatable<T> interface must contain a definition for an Equals
method that matches the signature that the interface specifies. As a result, you can count on a class that
implements IEquatable<T> to contain an Equals method with which an instance of the class can determine
whether it's equal to another instance of the same class.The definition of IEquatable<T> doesn’t provide an
implementation for Equals. The interface defines only the signature. In that way, an interface in C# is similar
to an abstract class in which all the methods are abstract. However, a class or struct can implement multiple
interfaces, but a class can inherit only a single class, abstract or not. Therefore, by using interfaces, we can
include behavior from multiple sources in a class.Here is a custom interface defined in C#:
// This interface defines the behavior of "having points."
public interface IPointy
{
// Implicitly public and abstract.
byte GetNumberOfPoints();
}
By convention, interfaces in the .NET base class libraries are prefixed with a capital letter “I.” When we are
creating your own custom interfaces, it is considered a best practice to do the same. The IPointy interface
defines a single method. However, .NET interface types are also able to define any number of properties. For
example, we could create the IPointy interface to use a read-only property rather than a traditional accessor
method:
// The pointy behavior as a read-only property.
public interface IPointy
{
byte Points{get;}
}

Normally interface types are quite useless on their own, as they are nothing more than a named collection of
abstract members. Given this, you cannot allocate interface types as you would a class or structure:
// Illegal to "new" interface types.
static void Main(string[] args)
{
IPointy p = new IPointy(); // Compiler error!
}

Implementation of Interfaces and Inheritance


To implement an interface member, the corresponding member of the implementing class must be public,
non-static, and have the same name and signature as the interface member.When a class or struct
implements an interface, the class or struct must provide an implementation for all of the members that the
interface defines. The interface itself provides no functionality that a class or struct can inherit in the way that
it can inherit base class functionality. However, if a base class implements an interface, any class that's
derived from the base class inherits that implementation.

Dept of MCA
18MCA51 [Programming using C#] 2020 19
// This class derives from System.Object and implements a single interface.
public class SomeClass : ISomeInterface
{...}
// This class also derives from System.Object and implements a single interface.
public class MyClass : object, ISomeInterface
{...}
// This class derives from a custom base class and implements a single interface.
public class AnotherClass : MyBaseClass, ISomeInterface
{...}
// This struct derives from System.ValueType and implements two interfaces.
public struct SomeStruct : ISomeInterface, IPointy
{...}
The following example shows an implementation of the IPointy interface. Given that the IPointy interface
defines a single property, this is not too much of a burden. However, if we are implementing an interface that
defines ten members, the type is now responsible for fleshing out the details of the ten abstract entities. //
Shape class

public class Shape


{
protected string PetName;
public Shape ()
{
PetName = “NoName”;
}
public Shape (string name)
{
PetName = name;
}
public virtual void Draw()
{
Console.WriteLine("Drawing {0} the Shape ", PetName);
}
}
// Hexagon now implements IPointy.
public class Hexagon : Shape, IPointy
{
public Hexagon(){ }
public Hexagon(string name) : base(name){ }
public override void Draw()
{ Console.WriteLine("Drawing {0} the Hexagon", PetName); }
// IPointy Implementation.
public byte Points
{
get { return 6; }
}
}
// Shape derived class named Triangle.
public class Triangle : Shape, IPointy
{
public Triangle() { }
public Triangle(string name) : base(name) { }

Dept of MCA
18MCA51 [Programming using C#] 2020 20
public override void Draw()
{
Console.WriteLine("Drawing {0} the Triangle", PetName); }
// IPointy Implementation.
public byte Points
{
get { return 3; }
}
}

Each class now returns its number of points to the caller when asked to do so. The class diagram shown in
Figure- 1 illustrates IPointy-compatibleclasses using the popular “lollipop” notation.

An interface has the following properties:

 An interface is like an abstract base class. Any class or struct that implements the interface must
implement all its members.

 An interface can't be instantiated directly. Its members are implemented by any class or struct that
implements the interface.

 Interfaces can contain events, indexers, methods, and properties.

 Interfaces contain no implementation of methods.

 A class or struct can implement multiple interfaces. A class can inherit a base class and also
implement one or more interfaces.

DIFFERENCE BETWEEN AN ABSTRACT CLASS AND AN INTERFACE:

 An Abstract class doesn't provide full abstraction but an interface does provide full abstraction; i.e.
both a declaration and a definition is given in an abstract class but not so in an interface.

Dept of MCA
18MCA51 [Programming using C#] 2020 21

 Using Abstract we cannot achieve multiple inheritance but using an Interface we can achieve multiple
inheritance.

 We cannot declare a member field in an Interface.

 We cannot use any access modifier i.e. public, private, protected, internal etc. because within an
interface by default everything is public.

 An Interface member cannot be defined using the keyword static, virtual, abstract or sealed.

ARRAYS OF INTERFACES:

Interfaces in C # provide a way to achieve runtime polymorphism. Using interfaces we can invoke functions
from different classes through the same Interface reference, whereas using virtual functions we can invoke
functions from different classes in the same inheritance hierarchy through the same reference. We can create
arrays of interfaces in same way create array of classes. Following is the example program to array of
interfaces.
using System;
using System.Collections.Generic;

namespace ArrayInterface
{
public interface IPointy
{
byte GetNumberOfPoints(); // Implicitly public and abstract.
void Draw();
}

public class Hexagon : IPointy


{
public Hexagon() { }
public Hexagon(string name) { }
public void Draw() // IPointy Implementation.
{
Console.WriteLine("-------------------------------");
Console.WriteLine("Drawing the Hexagon");
}
public byte GetNumberOfPoints()
{
return 6; // IPointy Implementation.
}
}
public class Triangle : IPointy
{
public Triangle() { }

Dept of MCA
18MCA51 [Programming using C#] 2020 22
public Triangle(string name) { }
public void Draw() // IPointy Implementation.
{
Console.WriteLine("-------------------------------");
Console.WriteLine("Drawing the Triangle");
}

public byte GetNumberOfPoints()


{
return 3; // IPointy Implementation.
}
}
class ArrayExample
{
static void Main(string[] args)
{
Console.WriteLine("Demonstrating arrays of interfaces");
IPointy[] obj = { new Triangle("Triangle"), new Hexagon("Hexagon"), new
Triangle() };
int i=0;
foreach (IPointy I in obj)
{
I.Draw();
Console.WriteLine("Number of Points are {0}\n",I.GetNumberOfPoints());
}

Console.ReadLine();
}
}
}

Dept of MCA

You might also like