DevAcademia
C++C#CPythonJava
  • C# Basics

  • C# Introduction
  • C# Get Started
  • C# Syntax
  • C# Output
  • C# Comments
  • C# Variables
  • C# Data Types
  • C# Type Casting
  • C# User Input
  • C# Operators
  • C# Math
  • C# Strings
  • C# Booleans
  • C# If...Else
  • C# Switch Statement
  • C# While Loop
  • C# For Loop
  • C# Break and Continue
  • C# Arrays
  • C# Files
  • C# OOP

  • C# OOP Introduction
  • C# Classes and Objects
  • C# Class Members
  • C# Constructors
  • C# Destructors
  • C# Access Modifiers
  • C# Properties
  • C# Inheritance
  • C# Polymorphism
  • C# Abstraction
  • C# Interfaces
  • C# Enums
  • C# Exceptions
  • C# Quizzes

  • C# Quiz Introduction
  • C# Basics

  • C# Introduction
  • C# Get Started
  • C# Syntax
  • C# Output
  • C# Comments
  • C# Variables
  • C# Data Types
  • C# Type Casting
  • C# User Input
  • C# Operators
  • C# Math
  • C# Strings
  • C# Booleans
  • C# If...Else
  • C# Switch Statement
  • C# While Loop
  • C# For Loop
  • C# Break and Continue
  • C# Arrays
  • C# Files
  • C# OOP

  • C# OOP Introduction
  • C# Classes and Objects
  • C# Class Members
  • C# Constructors
  • C# Destructors
  • C# Access Modifiers
  • C# Properties
  • C# Inheritance
  • C# Polymorphism
  • C# Abstraction
  • C# Interfaces
  • C# Enums
  • C# Exceptions
  • C# Quizzes

  • C# Quiz Introduction

Loading Cs tutorial…

Loading content
C# OOPTopic 50 of 55
←PreviousPrevNextNext→

C# Interface - Complete Guide

Introduction to C# Interfaces

An interface in C# is a reference type that can contain method signatures, properties, events, and indexers, but no implementation details (until default implementations introduced in C# 8.0). Interfaces define a contract that implementing classes or structs must follow.

Interfaces enable polymorphism and help achieve abstraction in C# programs. They allow different classes to be treated uniformly based on their common interface rather than their specific implementation, promoting loose coupling and easier maintenance.

Interface Declaration and Implementation

Interfaces are declared using the interface keyword and implemented by classes or structs using the : symbol. Unlike class inheritance, a type can implement multiple interfaces, providing flexibility in design.

Example
using System;

// Interface declaration
public interface IShape
{
    double CalculateArea();
    double CalculatePerimeter();
    string Name { get; }
}

// Interface for printable objects
public interface IPrintable
{
    void Print();
}

// Class implementing IShape and IPrintable
public class Circle : IShape, IPrintable
{
    public double Radius { get; set; }
    public string Name => "Circle";
    
    public Circle(double radius)
    {
        Radius = radius;
    }
    
    public double CalculateArea() => Math.PI * Radius * Radius;
    public double CalculatePerimeter() => 2 * Math.PI * Radius;
    
    public void Print()
    {
        Console.WriteLine($"Shape: {Name}");
        Console.WriteLine($"Radius: {Radius}");
        Console.WriteLine($"Area: {CalculateArea():F2}");
        Console.WriteLine($"Perimeter: {CalculatePerimeter():F2}");
    }
}

// Another class implementing IShape
public class Rectangle : IShape
{
    public double Width { get; set; }
    public double Height { get; set; }
    public string Name => "Rectangle";
    
    public Rectangle(double width, double height)
    {
        Width = width;
        Height = height;
    }
    
    public double CalculateArea() => Width * Height;
    public double CalculatePerimeter() => 2 * (Width + Height);
}

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("=== Interface Implementation Demo ===");
        
        Circle circle = new Circle(5);
        Rectangle rectangle = new Rectangle(4, 6);
        
        IShape shape1 = circle;
        IShape shape2 = rectangle;
        
        Console.WriteLine($"Circle Area: {shape1.CalculateArea():F2}");
        Console.WriteLine($"Rectangle Area: {shape2.CalculateArea():F2}");
        
        IPrintable printable = circle;
        Console.WriteLine("\nPrinting Circle info:");
        printable.Print();
        
        Console.WriteLine("\n=== Polymorphism with Interfaces ===");
        IShape[] shapes = { circle, rectangle };
        foreach (IShape shape in shapes)
        {
            Console.WriteLine($"{shape.Name}: Area = {shape.CalculateArea():F2}, Perimeter = {shape.CalculatePerimeter():F2}");
        }
    }
}
Output
=== Interface Implementation Demo ===
Circle Area: 78.54
Rectangle Area: 24.00

Printing Circle info:
Shape: Circle
Radius: 5
Area: 78.54
Perimeter: 31.42

=== Polymorphism with Interfaces ===
Circle: Area = 78.54, Perimeter = 31.42
Rectangle: Area = 24.00, Perimeter = 20.00

Interface Features and Best Practices

C# interfaces have evolved with new features in recent versions. Key aspects include explicit interface implementation, default interface methods (C# 8.0+), and interface inheritance.

Best practices for using interfaces include: favoring interface-based design, using meaningful names (often starting with 'I'), keeping interfaces focused and cohesive, and applying interfaces to enable dependency injection.

Example
using System;

// Base interface
public interface IAnimal
{
    string Name { get; }
    void MakeSound();
    
    // Default interface method (C# 8.0+)
    void Sleep()
    {
        Console.WriteLine($"{Name} is sleeping");
    }
}

// Interface inheritance
public interface IMammal : IAnimal
{
    int NumberOfLegs { get; }
    void Run();
}

// Explicit interface implementation example
public class Dog : IMammal
{
    public string Name => "Dog";
    public int NumberOfLegs => 4;
    
    public void MakeSound() => Console.WriteLine("Woof! Woof!");
    public void Run() => Console.WriteLine($"{Name} is running on {NumberOfLegs} legs");
    
    void IAnimal.Sleep()
    {
        Console.WriteLine($"{Name} is sleeping in its dog house");
    }
}

// Another class using default implementation
public class Cat : IAnimal
{
    public string Name => "Cat";
    public void MakeSound() => Console.WriteLine("Meow! Meow!");
}

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("=== Advanced Interface Features ===");
        
        Dog dog = new Dog();
        Cat cat = new Cat();
        
        IAnimal animal1 = dog;
        IAnimal animal2 = cat;
        IMammal mammal = dog;
        
        Console.WriteLine("=== Animal Behaviors ===");
        animal1.MakeSound();
        animal2.MakeSound();
        
        Console.WriteLine("\n=== Sleep Behaviors ===");
        animal1.Sleep();
        animal2.Sleep();
        
        Console.WriteLine("\n=== Mammal Specific ===");
        mammal.Run();
        
        Console.WriteLine("\n=== Explicit Implementation Demo ===");
        Dog myDog = new Dog();
        IAnimal myAnimal = myDog;
        myAnimal.Sleep();
    }
}
Output
=== Advanced Interface Features ===
=== Animal Behaviors ===
Woof! Woof!
Meow! Meow!

=== Sleep Behaviors ===
Dog is sleeping in its dog house
Cat is sleeping

=== Mammal Specific ===
Dog is running on 4 legs

=== Explicit Implementation Demo ===
Dog is sleeping in its dog house
Test your knowledge: C# Interface - Complete Guide
Quiz Configuration
4 of 8 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 5 min
C# OOPTopic 50 of 55
←PreviousPrevNextNext→