C# Interfaces — Complete Beginner Guide
Learning Objectives
- Define and implement interfaces
- Implement more than one interface
- Cast objects to interface types
- Use interface default implementations
- Choose interfaces over inheritance appropriately
What Is an Interface
An interface is a contract of behavior. It lists methods, properties, or events that a type promises to support without dictating full implementation details.
interface IPrintable
{
void Print();
}
class Report : IPrintable
{
public void Print()
{
Console.WriteLine("Printing report");
}
}
Report r = new Report();
r.Print();
Types implement interfaces with a colon, just like inheritance, and must provide bodies for required members.
Why Interfaces Matter
Interfaces decouple what a type can do from how it does it. Callers depend on the contract, not a concrete class. That makes testing and swapping implementations easier.
| Inheritance | Interface |
|---|---|
| Shares code and state | Shares a capability contract |
| Single base class in C# | Many interfaces allowed |
| Strong is-a link | Can-do relationship |
| May include fields | No instance fields in classic interfaces |
Implementing Multiple Interfaces
A class can adopt several contracts at once.
interface IReadable
{
void Read();
}
interface ISaveable
{
void Save();
}
class Document : IReadable, ISaveable
{
public void Read()
{
Console.WriteLine("Reading document");
}
public void Save()
{
Console.WriteLine("Saving document");
}
}
Document doc = new Document();
doc.Read();
doc.Save();
IReadable asReadable = doc;
asReadable.Read();
Assigning to an interface reference lets code depend only on the capability it needs.
Explicit Interface Implementation
When two interfaces define members with the same name, explicit implementation removes ambiguity.
interface IA
{
void Run();
}
interface IB
{
void Run();
}
class Runner : IA, IB
{
void IA.Run()
{
Console.WriteLine("IA run");
}
void IB.Run()
{
Console.WriteLine("IB run");
}
}
Runner r = new Runner();
IA a = r;
IB b = r;
a.Run();
b.Run();
Explicit members are accessible only through the matching interface type.
Interfaces with Properties
interface INamed
{
string Name { get; }
}
class User : INamed
{
public string Name { get; }
public User(string name)
{
Name = name;
}
}
User u = new User("Kira");
Console.WriteLine(u.Name);
Default Interface Members
Modern C# can provide default implementations so adding a member does not break every implementer at once.
interface IGreeter
{
string Hello()
{
return "Hello";
}
}
class SilentGreeter : IGreeter
{
}
class LoudGreeter : IGreeter
{
public string Hello()
{
return "HELLO";
}
}
IGreeter s = new SilentGreeter();
IGreeter l = new LoudGreeter();
Console.WriteLine(s.Hello());
Console.WriteLine(l.Hello());
Default members are invoked through the interface, which keeps compatibility while evolving contracts.
Designing Good Interfaces
- Keep interfaces small and focused; prefer one clear purpose
- Name them with capability style words such as IReadable or ICache
- Hide construction details behind factories when needed
- Prefer composition of interfaces over deep base class trees
- Test against interfaces with fake implementations
A small role based example
Imagine a document system where one type can be printed, another can be archived, and a third can do both. Instead of a wide base class, define narrow interfaces for each capability. Callers then depend only on the interface they truly need. A print service accepts printable items. An archive service accepts archivable items. A versatile class implements both when it genuinely supports both roles.
This approach keeps optional features out of types that do not need them.
Common Mistakes
Fat interfaces
Bundling unrelated methods forces classes to implement bloat they do not need. Split contracts by role.
Using interfaces only as documentation
An interface without polymorphic use adds little value. Design call sites that accept the contract.
Confusing inheritance reuse with contracts
If you only need shared helpers, composition often beats inheritance. Reserve inheritance for true is-a designs.
Naming interfaces inconsistently
Pick a convention and stick to it across the codebase. Consistent prefixes and role based names make discovery easier in autocomplete lists and documentation.
Key Takeaways
💡
- Interfaces define capability contracts without full state design
- A class can implement multiple interfaces at once
- Interface references enable flexible, testable call sites
- Explicit implementation resolves member name collisions
- Default interface members help contracts evolve safely
Practice Questions
- What relationship does an interface express compared with base class inheritance?
- How does C# show that a class implements two interfaces?
- When would you use explicit interface implementation?
- What are default interface members useful for?
- Design interfaces named IWritable and IReadable, then create a class that implements both and demonstrate each through interface variables.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions