An interface declares members that implementing classes must provide. By convention, interface names start with I.
class Card : IPayment
A class can implement many interfaces.
Interfaces enable loose coupling and are central to dependency injection in ASP.NET Core.
💡 Key Takeaways: C# Interfaces
Mastering C# Interfaces helps you write clean and reliable C# code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
C# Interfaces Code Example
C#
IPayment[] methods = { new Card(), new JazzCash() };
decimal amount = 10000m;
foreach (var m in methods)
{
Console.WriteLine($"{m.Name}: fee {m.Fee(amount)}");
}
interface IPayment
{
string Name { get; }
decimal Fee(decimal amount);
}
class Card : IPayment
{
public string Name => "Card";
public decimal Fee(decimal amount) => amount * 0.025m;
}
class JazzCash : IPayment
{
public string Name => "JazzCash";
public decimal Fee(decimal amount) => 20m;
}
Output
Card: fee 250.000
JazzCash: fee 20
Run this example on your own computer. The "Get Started" lesson shows how to set it up.