</>
Skip to content
C# lessons (24/34)

C# — Interfaces

Basic interface

using System;

public interface ILoggable
{
    void Log(string message);
}

public class ConsoleLogger : ILoggable
{
    public void Log(string message)
    {
        Console.WriteLine($"[LOG] {message}");
    }
}

class Program
{
    static void Main()
    {
        ILoggable logger = new ConsoleLogger();
        logger.Log("Application started");
    }
}

Multiple interfaces

using System;

public interface ISerializable
{
    string Serialize();
}

public interface IValidatable
{
    bool Validate();
}

public class User : ISerializable, IValidatable
{
    public string Name { get; set; }
    public int Age { get; set; }

    public string Serialize() => $"{{\"name\":\"{Name}\",\"age\":{Age}}}";
    public bool Validate() => !string.IsNullOrEmpty(Name) && Age > 0;
}

class Program
{
    static void Main()
    {
        var user = new User { Name = "Alice", Age = 30 };
        Console.WriteLine(user.Serialize());
        Console.WriteLine($"Valid: {user.Validate()}");
    }
}

Interface properties and methods

using System;

public interface IMathOperations
{
    double Add(double a, double b);
    double Multiply(double a, double b);
    double Pi { get; }
}

public class MathHelper : IMathOperations
{
    public double Add(double a, double b) => a + b;
    public double Multiply(double a, double b) => a * b;
    public double Pi => 3.14159;
}

class Program
{
    static void Main()
    {
        IMathOperations math = new MathHelper();
        Console.WriteLine(math.Add(3, 4));       // 7
        Console.WriteLine(math.Pi);              // 3.14159
    }
}

Default interface methods (C# 8+)

using System;

public interface IRepository
{
    void Save(string data);

    // Default implementation
    void SaveDefault()
    {
        Save("default data");
    }
}

public class SqlRepository : IRepository
{
    public void Save(string data)
    {
        Console.WriteLine($"Saving to SQL: {data}");
    }
    // SaveDefault is inherited from interface
}

class Program
{
    static void Main()
    {
        IRepository repo = new SqlRepository();
        repo.Save("user data");
        repo.SaveDefault(); // Uses default implementation
    }
}

Interface inheritance

using System;

public interface IShape
{
    double Area();
    string Type { get; }
}

public interface IResizable : IShape
{
    void Resize(double factor);
}

public class Circle : IResizable
{
    public double Radius { get; private set; }
    public string Type => "Circle";

    public Circle(double radius) => Radius = radius;
    public double Area() => Math.PI * Radius * Radius;
    public void Resize(double factor) => Radius *= factor;
}

class Program
{
    static void Main()
    {
        IResizable c = new Circle(5);
        Console.WriteLine($"Area: {c.Area():F2}");
        c.Resize(2);
        Console.WriteLine($"After resize: {c.Area():F2}");
    }
}

Interface segregation

using System;

// Good: small, focused interfaces
public interface IReadable
{
    string Read();
}

public interface IWritable
{
    void Write(string data);
}

// Implement only what's needed
public class FileReader : IReadable
{
    public string Read() => "file content";
}

public class FileWriter : IWritable
{
    public void Write(string data) => Console.WriteLine($"Writing: {data}");
}

public class FileHandler : IReadable, IWritable
{
    public string Read() => "file content";
    public void Write(string data) => Console.WriteLine($"Writing: {data}");
}

Explicit interface implementation

using System;

public interface IA
{
    void Method();
}

public interface IB
{
    void Method();
}

public class MyClass : IA, IB
{
    // Must be called through interface
    void IA.Method() => Console.WriteLine("IA.Method");
    void IB.Method() => Console.WriteLine("IB.Method");

    // Public method (called on class)
    public void Method() => Console.WriteLine("MyClass.Method");
}

class Program
{
    static void Main()
    {
        var obj = new MyClass();
        obj.Method();                    // MyClass.Method

        ((IA)obj).Method();              // IA.Method
        ((IB)obj).Method();              // IB.Method
    }
}

Interface vs abstract class

FeatureInterfaceAbstract Class
Multiple inheritance✓✗
State (fields)✗ (C# 8+ can have default)✓
Constructors✗✓
Access modifiersPublic only (C# 7)Any
ImplementationDefault methods (C# 8+)Full or partial

Mini Practice

Write C# code that:

  1. Defines IDrawable and IAnimatable interfaces
  2. Implements both in a GameCharacter class
  3. Uses default interface methods
  4. Demonstrates explicit interface implementation

Up Next

In the next lesson, you'll learn about Enums — enumerations and flags in C#.

Related Topics

Frequently Asked Questions about Interfaces

What is Interfaces in C#?

Interfaces is a fundamental concept in C#. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Interfaces?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Interfaces.

Why is Interfaces important in C#?

Interfaces is essential for C# development. Understanding this concept will help you write better code and solve real-world problems more effectively.