Interface Basics
An interface is a list of promises, such as 'anything that can fly must have a fly action'. It says what must be done but not how.
In this page:
Syntax
interface IInterfaceName
{
ReturnType MethodName();
}
class ClassName : IInterfaceName
{
public ReturnType MethodName() { }
}
Interface Basics
An interface declares a contract of members that implementing classes must provide, but supplies no implementation of its own (aside from default methods).
It's declared with interface and conventionally named starting with I, like IShape. Interfaces define *what* a type can do, not *how* it does it.
Note:
Interface members are implicitly public — you never write an access modifier on them.
Example: Interface Basics
using System;
interface IGreeter
{
void Greet();
}
class EnglishGreeter : IGreeter
{
public void Greet()
{
Console.WriteLine("Hello!");
}
}
class Program
{
static void Main(string[] args)
{
IGreeter g = new EnglishGreeter();
g.Greet();
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Trying to create an object from an interface directly, which is a compile error.
- Adding fields to an interface, which is not allowed.
- Forgetting that interface members are public by default and adding an access modifier where not needed.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: