0
0
C Sharp (C#)programming~5 mins

Interface declaration syntax in C Sharp (C#)

Choose your learning style9 modes available
Introduction

An interface in C# is like a promise that a class will have certain methods or properties. It helps organize code and makes sure different parts work well together.

When you want different classes to share the same set of methods or properties.
When you want to write code that can work with different types of objects in the same way.
When you want to separate what a class does from how it does it.
When you want to create a contract that multiple classes must follow.
When you want to make your code easier to test and maintain.
Syntax
C Sharp (C#)
interface InterfaceName
{
    // Method signatures
    ReturnType MethodName(ParameterList);
    
    // Property signatures
    PropertyType PropertyName { get; set; }
}

The keyword interface starts the declaration.

Interfaces only have method and property signatures, no actual code inside methods.

Examples
This interface says any class that uses it must have a Speak method.
C Sharp (C#)
interface IAnimal
{
    void Speak();
}
This interface requires a Wheels property and a Drive method.
C Sharp (C#)
interface IVehicle
{
    int Wheels { get; set; }
    void Drive();
}
This interface defines two methods for shapes to calculate area and perimeter.
C Sharp (C#)
interface IShape
{
    double Area();
    double Perimeter();
}
Sample Program

This program shows an interface IGreet with a method SayHello. Two classes, Person and Robot, implement this interface with their own versions of SayHello. The Main method calls these methods through the interface.

C Sharp (C#)
using System;

interface IGreet
{
    void SayHello();
}

class Person : IGreet
{
    public void SayHello()
    {
        Console.WriteLine("Hello from Person!");
    }
}

class Robot : IGreet
{
    public void SayHello()
    {
        Console.WriteLine("Beep boop, hello from Robot!");
    }
}

class Program
{
    static void Main()
    {
        IGreet person = new Person();
        IGreet robot = new Robot();

        person.SayHello();
        robot.SayHello();
    }
}
OutputSuccess
Important Notes

Interfaces cannot contain fields or constructors.

A class can implement multiple interfaces, helping organize different behaviors.

Interfaces help with writing flexible and testable code.

Summary

Interfaces define a contract with method and property signatures only.

Classes use interfaces to promise they have certain methods or properties.

This helps write organized, flexible, and reusable code.