npub1u6…v0yg2 on Nostr: Learn: Interface An interface is a contract: members a class must provide. It can't ...
Learn: Interface
An interface is a contract: members a class must provide. It can't hold instance data (no fields); since C# 8 it may give a method a default body.
A class can implement many interfaces.
Use it when: different classes should be usable the same way, for DI and testing with fakes, or plug-ins.
```csharp
IShape[] shapes = { new Square(2), new Circle(1) };
foreach (var s in shapes) Console.WriteLine(s.Area().ToString("0.00"));
interface IShape { double Area(); }
record Square(double Side) : IShape { public double Area() => Side * Side; }
record Circle(double R) : IShape { public double Area() => Math.PI * R * R; }
```
It prints 4.00, then 3.14.
Read more:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/interface#tip · TIP-048
Published at
2026-10-28 10:38:27 UTCEvent JSON
{
"id": "5dca0d7a9e8b4c911d2e01f18e6829182fb4bab6c6099b47478ebe544144a4bc",
"pubkey": "e68a0856e90d9997b1f721e905249896412dd570399a987b2e8fd5e7fcfe2279",
"created_at": 1793183907,
"kind": 1,
"tags": [
[
"t",
"tip"
]
],
"content": "Learn: Interface\n\nAn interface is a contract: members a class must provide. It can't hold instance data (no fields); since C# 8 it may give a method a default body.\nA class can implement many interfaces.\nUse it when: different classes should be usable the same way, for DI and testing with fakes, or plug-ins.\n\n```csharp\nIShape[] shapes = { new Square(2), new Circle(1) };\nforeach (var s in shapes) Console.WriteLine(s.Area().ToString(\"0.00\"));\n\ninterface IShape { double Area(); }\nrecord Square(double Side) : IShape { public double Area() =\u003e Side * Side; }\nrecord Circle(double R) : IShape { public double Area() =\u003e Math.PI * R * R; }\n```\n\nIt prints 4.00, then 3.14.\n\nRead more: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/interface\n\n#tip · TIP-048",
"sig": "be16961aca2fc3d97a6539866a199decb49af79cf24eb73acf8594185d2415c4f4032716fd47bb0aa933799102323d42a765acc3b011c4a0433b1ffa1b55fea5"
}