Click here to Skip to main content
15,879,326 members
Articles / All Topics

Interfaces

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
18 Dec 2015CPOL2 min read 5K   1  
Interfaces

In this post, we’ll talk about Interfaces. Interfaces are basically constraints which Implementing class must follow. In one way, it is similar to abstract class but doesn’t act as base class. C# doesn’t have multiple inheritance. You can inherit from only one class but you can implement as many interfaces as you like. Also, one point to understand is that access modifiers like private, public, protected, etc. are not legal in case of interfaces. Hence, without wasting time, let’s jump into the demos.

Below is the simple interface in its plain form.

JavaScript
namespace InterfaceDemo
{
    interface ITransaction
    {
        void doTransaction();
        double getAmount { get; }
    }
}

Now, let us go ahead and create one class which implements the same. Below is the default implementation for the same. You may also notice that since I am not having setter in interface, hence in Implementation that came as private setter which means value can be set from constructor.

JavaScript
namespace InterfaceDemo
{
    class Transaction :ITransaction
    {
        public void doTransaction()
        {
            throw new System.NotImplementedException();
        }

        public double getAmount { get; private set; }
    }
}

Below is the modified code for class implementation.

JavaScript
using System;

namespace InterfaceDemo
{
    class Transaction : ITransaction
    {
        //Not part of interface
        public void startTransaction()
        {
            Console.WriteLine("Started doing Transaction");
        }
        public void doTransaction()
        {
            Console.WriteLine("Doing Cash Transaction");
        }

        public double getAmount
        {

            get { return 10000; }
        }
    }
}

Now, let us go ahead and use the same in main class. While writing the class, you can see available properties and methods to get exposed.

17th

Below is the main class in its finished form.

JavaScript
using System;

namespace InterfaceDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Transaction transaction = new Transaction();

            transaction.startTransaction();
            transaction.doTransaction();
            Console.WriteLine(transaction.getAmount);
            Console.ReadLine();
        }
    }
}

Now, when I run the same, it will produce the following output:

20th

However, it is also perfectly legal to have a variable of type Interface and instantiate a class like shown below. But, while doing so, here I won’t be having method access which is declared and implemented explicitly in class.

18th

JavaScript
using System;

namespace InterfaceDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            ITransaction transaction = new Transaction();
            transaction.doTransaction();
            Console.WriteLine(transaction.getAmount);
            //Transaction transaction = new Transaction();

            //transaction.startTransaction();
            //transaction.doTransaction();
            //Console.WriteLine(transaction.getAmount);
            Console.ReadLine();
        }
    }
}

With the above change in place, it will print the following output:

19th

Also, we can have main method like shown below:

JavaScript
using System;

namespace InterfaceDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var transaction = new Transaction();
            transaction.startTransaction();
            transaction.doTransaction();
            Console.WriteLine(transaction.getAmount);

            //Assigned the object to Interface variable
            ITransaction iTransaction = transaction;
            //Here also only interface stuffs will be available
            //However, if at all we would like to transaction explicit method available, 
	    //then we need to cast like shown below
            Transaction transactionObj = iTransaction as Transaction;
            //Here, as keyword will examine the iTransaction and if it is of type Transaction, 
	    //then it will return Transaction
            //else will return null. Hence, null check is recommended here
            if(transactionObj!=null)
                transactionObj.startTransaction();

            Console.ReadLine();

        }
    }
}

Here, I have used cast operator as to check whether the object is of type class or interface. And, this will produce the following output:

21th

Download link: https://github.com/rahulsahay19/InterfaceDemo

With this, I would like to wrap this session here. Thanks for joining me.

Thanks,
Rahul Sahay
Happy coding!

Image 6

This article was originally posted at http://myview.rahulnivi.net?p=2531

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Publicis Sapient
India India
Hey there, it's Rahul Sahay! I'm thrilled to be a platform specialist at Publicis Sapient, where I get to work on some exciting projects. I've been honing my skills in various aspects of the software development life cycle for more than 15 years, with a primary focus on web stack development. I've been fortunate to have contributed to numerous software development initiatives, ranging from client applications to web services and websites. Additionally, I enjoy crafting application architecture from scratch, and I've spent most of my time writing platform agnostic and cloud agnostic code. As a self-proclaimed code junkie, software development is more than just a job to me; it's a passion! And I consider myself lucky to have worked with an array of cutting-edge technologies, from .NetCore to SpringBoot 3, from Angular to React, and from Azure to AWS and many more cousin technologies...

- 🔭 I’m currently working @ below tech stacks
- Microservices,
- Distributed Systems,
- Spring Boot
- Spring Cloud
- System Design,
- Docker,
- Kubernetes,
- Message Queues,
- ELK Stack
- DotNetCore,
- Angular,
- Azure

- 💬 Ask me anything about my articles [My View](https://myview.rahulnivi.net/)
- 📫 How to reach me: [@rahulsahay19](https://twitter.com/rahulsahay19)
- 📫 Github: [@rahulsahay19](https://github.com/rahulsahay19)

Comments and Discussions

 
-- There are no messages in this forum --