Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

C# Interface:


Sure! In C#, an interface is a blueprint for a class. It defines a set of methods and properties that a class must implement if it implements that interface. Think of an interface as a contract that a class agrees to fulfill. Interfaces provide a way to achieve abstraction and polymorphism in C#.

Here's a simple explanation with an example:

Suppose we want to create an interface called IAnimal that defines a method MakeSound(), and then we implement this interface in two different classes: Dog and Cat.

Example

using System;

// Interface defining the blueprint for animals
interface IAnimal
{
void MakeSound(); // Method signature for making sound
}

// Class implementing the IAnimal interface
class Dog : IAnimal
{
public void MakeSound()
{
Console.WriteLine("Dog barks");
}
}

// Class implementing the IAnimal interface
class Cat : IAnimal
{
public void MakeSound()
{
Console.WriteLine("Cat meows");
}
}

class Program
{
static void Main(string[] args)
{
IAnimal dog = new Dog(); // Creating a Dog object using IAnimal interface
IAnimal cat = new Cat(); // Creating a Cat object using IAnimal interface

dog.MakeSound(); // Calls the MakeSound() method of Dog class
cat.MakeSound(); // Calls the MakeSound() method of Cat class
}
}

In this example:

Interfaces are useful for defining contracts that classes must adhere to, enabling code to be more flexible, modular, and easy to maintain. They also facilitate code reuse and promote loosely coupled designs.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java