Skip to content

Implementing an interface

Context: A class or struct implements an interface by providing concrete implementations for all its members.

class ClassName : InterfaceName
{
// implement all interface members
}
public interface IPerson
{
string Name { get; set; }
void Introduce();
}
public class Student : IPerson
{
public string Name { get; set; }
public void Introduce() => Console.WriteLine($"I'm {Name}, a student");
}
public class FileManager : IReadable, IWritable
{
public string Read() => "data";
public void Write(string data) { /* ... */ }
}

You can use an interface type to hold any implementing object.

IPerson person = new Student { Name = "Alice" };
person.Introduce(); // works