Defining interfaces
Learn to define a contract with interface.
Defining an interface
An interface is a contract that the implementing class must follow. It contains method signatures but no bodies; it cannot hold fields. Declaration: interface IGreeter { string Greet(string name); }.
When a class implements an interface, it must write the body of every method. This lets different classes follow the same contract. Interfaces cannot be instantiated with new; they are used through instances of implementing classes.
Interface declaration
An interface declaration starts with the interface keyword. The body is in curly braces and each method signature ends with a semicolon: string Greet(string name);.
Methods are not marked public; interface members are public by default. Interface names usually start with an I prefix: IGreeter, IShape, IComparable. This avoids confusion with classes and follows .NET convention.
Exercise Greeter interface
Define the IGreeter interface with the string Greet(string name); method signature. EnglishGreeter and Main are already in place; you only add the interface.
Show example solution
Add `interface IGreeter { string Greet(string name); }`.
Example solution:
using System;
interface IGreeter
{
string Greet(string name);
}
class EnglishGreeter : IGreeter
{
public string Greet(string name)
{
return "Hello " + name;
}
}
class Program
{
static void Main()
{
IGreeter g = new EnglishGreeter();
Console.WriteLine(g.Greet("Alex"));
}
}
Test yourself
-
Which statement about interfaces is correct?
- An interface can hold fields.
- An interface is a contract and the implementing class provides the methods.
- An interface can be instantiated with new.
- An interface can be implemented by only one class.
Show answer
An interface is a contract and the implementing class provides the methods. — Correct. An interface is a contract; the implementing class provides the methods.
-
Fill in the blank: interface method
interface IGreeter { ____; }Show answer
interface IGreeter { string Greet(string name); } -
Match: interface concepts
- interface
- contract
- bodyless signature
- ends with semicolon
- I prefix
- IShape, IGreeter
- new IGreeter()
- invalid