Skip to main content

Interface with real life Examples


Interfaces with real life examples


An interface is a programming structure/syntax that allows the computer to enforce certain properties on an object (class). For example, say we have a car class and a tricyclic class and a truck class. Each of these three classes should have a start engine() action. How the "engine is started" for each vehicle is left to each particular class, but the fact that they must have a start engine action is the domain of the interface.

The syntax of an Interface

We can implement single interface or multiple interfaces to the class. By default interfaces are public.
We declare interface by using "interface" keyword.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CsharpnaijaInterfaceTutorial
{
    interface IEngine
    {
        void Start();
    }
}
Inside the {} of the interface is a list of functions that must be found in any object that implements the interface in this Start().

Implementation


    public class Car : IEngine
    {
        public void Start()
        {
            Console.Write("Car Started.");
        }
    }

   



    public class Truck : IEngine
    {
        public void Start()
        {
            Console.Write("Truck Started.");
        }
    }

    public class Tricyclic : IEngine
    {
        public void Start()
        {
            Console.Write("Tricyclic Started.");
        }
    }




From the above code snippets, we ca see that an Interface IEngine provides a contract that any other class that will implement the interface must a method implementation of the method signature provided by the interface.

The Car, Truck and Tricyclic classes implement the IEngine interface and provide different implementation for the method signature.

Let’s now see how to use the classes in our application

using System;

namespace InterfaceTutorial
{
    class Program
    {
        static void Main(string[] args)
        {
            var car = new Car();
            var truck = new Truck();
            var tricyclic = new Tricyclic();

            Console.WriteLine("Below are the Implementations of Start method for different vehicle");

            Console.WriteLine();
            car.Start();
            Console.WriteLine();
            truck.Start();
            Console.WriteLine();
            tricyclic.Start();
            Console.WriteLine();

            Console.ReadLine();
        }
    }
}




From the above code, we see that instances of Car, Truck and Tricyclic respectively and also called the start method of individual instance to print their start status to the console as shown below.


Another real life example of an interface

using System;
namespace InterfaceTutorial
{
    interface IAccount
    {
        void Deposit();
        void Withdraw();
    }

    public class Saving : IAccount
    {
        public void Deposit()
        {
            Console.WriteLine("Deposit to Saving Account");
        }

        public void Withdraw()
        {
            Console.WriteLine("Withdraw from Saving Account");
        }
    }
    public class Current : IAccount
    {
        public void Deposit()
        {
            Console.WriteLine("Deposit to Current Account");
        }

        public void Withdraw()
        {
            Console.WriteLine("Withdraw from Current Account");
        }
    }
}

In banking system in Nigeria we have Saving, Current, Fixed Deposit etc Accounts

To model this scenario, we create an interface of Account with the type of operations we want e.g. Deposit and Withdrawal such that Deposit and Withdraw are method signatures in the IAccount interface for any class to provide the implementation based on the account needed as modelled in the above code.

Benefits of using an interface
Below are some of the importance of using interfaces in our codes
o   Implemented interface enforces the class like a standard contract to provide all implementation of interface members.
o   In architecting the project we can define the proper naming conventions of methods, properties in an interface so that while implementing in a class we use the name conventions.
o   We can use the "interface" as a pointer in the different layers of applications.
o   We can use an interface for implementing run time polymorphism.

The two ways of implementing interfaces are

Explicit and Implicit
Explicit implementation

To implement an interface explicitly we have to define an interface name followed by (".") dot operator then the method name.

For example

        public void IEngine.Start()
        {
            Console.Write("Truck Started.");
        }
 We use explicit implementation of interface when we have two different interfaces with same method name.

Implicit implementation

To implement an interface implicitly, we have to implement the interface name after the class name using colon ":" operator as shown in below snipped code.
For example

    public class Truck : IEngine
    {
        public void Start()
        {
            Console.Write("Truck Started.");
        }
    }
An interface has the following properties:
·         An interface is like an abstract base class with only abstract members. 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 (but in C# 8.0, Interfaces can have default implementation for methods).
·         A class or struct can implement multiple interfaces. A class can inherit a base class and also implement one or more interfaces.

Comments

  1. This Interface will be helpful & useful to both Students & their lecturers. Thank u.

    ReplyDelete
  2. Your true color has started coming out as a DEVELOPER.
    Who say Marriage is NOT Good

    ReplyDelete
  3. I adore your work and expect online learning platform for people to register and take a course from you.

    ReplyDelete
    Replies
    1. Yes, that is already on the pipeline

      Delete
    2. I already have course for beginners to learn software development

      Delete
  4. This is first of its kind in teaching C#, especially that it's coming from a Nigerian.✌️

    ReplyDelete

Post a Comment

Popular posts from this blog

Classes in C# Explained

C# Class Explained A class is nothing but an encapsulation of properties and methods that are used to represent a real-time entity, as explained by Guru99 . For instance, if you want to work with Guest’s data as in our previous DataDriven Web application . The properties of the Guest would be the Id, GuestName, Address, Phone number etc of the Guest. The methods would include the entry and modification of Guest data. All of these operations can be represented as a class in C# as shown below. using System; namespace CsharpnaijaClassTutorial {     public class Guest     {         public int Id { get ; set ; }         public string GuestName { get ; set ; }         public string Address { get ; set ; }         public string WhomToSee { get ; set ; }     ...

ASP.NET MVC Views

Views in ASP.NET MVC Application explained Find a related article By  Steve Smith  and  Luke Latham from Microsoft Corporation here In the Model-View-Controller (MVC) pattern, the  view  handles the application's data presentation and user interaction. A view is an HTML template with embedded  Razor markup . Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET MVC, views are  .cshtml  files that use the  C# programming language  in Razor markup. Usually, view files are grouped into folders named for each of the application's  controllers . The folders are stored in a  Views  folder at the root of the application as shown: The  Home  controller is represented by a  Home  folder inside the  Views  folder.  The  Home  folder contains the views for the  About ,  Contact , and  Index...

ASP.NET MVC Routing

ASP.NET MVC Routing ASP.NET MVC routing is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match. Routing pattern is as follows A URL is requested from a browser, the URL is parsed (that is, break into controller and action), the parsed URL is compared to registered route pattern in the framework’s route table, if a route is found, its process and send response to the browser with the required response, otherwise, the HTTP 404 error is send to the browser. Route Properties ASP.NET MVC routes are res...