C# Classes, Interfaces and Generics vs TypeScript
On this page
Learning Objective
Write C# classes, interfaces, and generic types confidently, explain nominal versus structural typing and why it changes how you design abstractions, and use access modifiers, constructors, and generic constraints to build small, safe, reusable components.
Concept Explanation
TypeScript uses structural typing: if an object has the right shape it satisfies a type, regardless of what it was declared as. C# uses nominal typing: a class satisfies an interface only if it explicitly declares that it implements it. The consequence for design is that C# abstractions are deliberate contracts. When you write an interface such as IEmailSender, every implementation names it, tools can find all implementers, and the compiler guarantees that each one provides every member. This is the foundation of dependency injection, which you will meet in Day 8, and it is the same idea behind Angular's injectable services with an abstract class or token.
A class in C# combines state and behavior, with explicit access modifiers. Public members are visible everywhere, private members only inside the class, internal members inside the same project, and protected members to subclasses. Default to the narrowest access that works. From a security perspective this is more than tidiness: a class that exposes only the operations it intends to, and keeps its invariants behind private state, is much harder to misuse. Constructors let you require the collaborators a class needs, and primary constructors, introduced in C# 12, let you declare them concisely in the class header.
Properties replace the getter and setter methods you may know from Java or older TypeScript. A property looks like a field to callers but can validate, compute, or restrict access. The init accessor allows a property to be set only during object construction, giving you immutability with the convenience of object initializer syntax. Combined with the required modifier, which forces callers to supply a value, it lets you build types where an invalid half-constructed object cannot exist, which is a useful defensive technique for domain models.
Generics in C# are reified: the runtime knows the actual type arguments, unlike TypeScript where they vanish after compilation. You can therefore write a List of int that stores real integers with no boxing, and reflection can inspect the closed type. You can also constrain a type parameter with where clauses, for example where T : class, IEntity, new(), so the generic code can safely call members the constraint guarantees. Common generic abstractions you will use constantly include IEnumerable of T, Task of T, ILogger of T, and IOptions of T.
| Feature | TypeScript | C# |
|---|---|---|
| Typing model | Structural | Nominal, declared with a colon after the class name |
| Interface implementation | Implicit by shape | Explicit: class Foo : IFoo |
| Access control | public, private (compile time only) | public, private, protected, internal (enforced at runtime) |
| Generics | Erased at compile time | Reified, checked by the runtime |
| Generic constraints | extends | where T : constraint |
| Required construction data | Constructor parameters or optional fields | Constructors, init, and the required modifier |
Worked Example: A Generic Repository Contract with a Constraint
The example defines an interface, a generic in-memory implementation, and a type with required, init-only properties. It uses a generic constraint so the repository can rely on every entity having an Id. This shape reappears in Phase 4 when the store becomes SQL Server.
public interface IEntity
{
Guid Id { get; }
}
public interface IRepository<T> where T : IEntity
{
Task<T?> GetAsync(Guid id);
Task AddAsync(T item);
Task<IReadOnlyList<T>> ListAsync();
}
public sealed class InMemoryRepository<T> : IRepository<T> where T : IEntity
{
private readonly Dictionary<Guid, T> _items = new();
public Task<T?> GetAsync(Guid id) =>
Task.FromResult(_items.TryGetValue(id, out var item) ? item : default);
public Task AddAsync(T item)
{
_items[item.Id] = item;
return Task.CompletedTask;
}
public Task<IReadOnlyList<T>> ListAsync() =>
Task.FromResult<IReadOnlyList<T>>(_items.Values.ToList());
}
public sealed class Note : IEntity
{
public Guid Id { get; } = Guid.NewGuid();
public required string Title { get; init; } // must be supplied, cannot change later
public string? Body { get; init; }
}
// Usage: the compiler enforces every rule above.
IRepository<Note> repo = new InMemoryRepository<Note>();
await repo.AddAsync(new Note { Title = "Day 4" });
// new Note { } -> compile error: Title is requiredNotice that callers depend on IRepository of Note, not on the concrete class. Swapping the in-memory version for a database version later changes one line of registration and nothing else, which is exactly the property dependency injection is designed to give you.
Real-World Examples
- The ASP.NET Core framework is built around small generic interfaces. ILogger of T gives each class a logger that automatically categorizes messages by the type that wrote them, and IOptions of T delivers strongly typed configuration. Because the type arguments are real at runtime, the framework can use them to route and label behavior with no string keys.
- The C# language team added the required modifier in C# 11 and primary constructors in C# 12 in response to boilerplate and half-initialized object bugs that large codebases kept hitting. Both features exist to make invalid states harder to construct, which reflects the broader design direction toward types that prevent mistakes.
Review Questions & Answers
C# is nominally typed, so a class opts in to a contract by naming the interface, and the compiler then verifies that every member is implemented. This makes contracts intentional rather than accidental: two unrelated classes that happen to share method names do not silently become interchangeable. It also lets tools and dependency injection containers find implementations reliably.
They let you create objects that are fully initialized at construction and cannot be mutated afterward. The required modifier makes the compiler reject any creation that omits the property, and init prevents later changes. This avoids the half-built object bug where code forgets to set a field, and it makes shared objects safe to pass between threads without locking.
Because the runtime knows the real type arguments, generic code in C# can store value types without boxing, can be inspected through reflection, and can be used by frameworks that resolve services by generic type. TypeScript generics exist only for compile-time checking, so nothing about them is available when the program runs. In practice this is what makes injecting an ILogger of a specific class possible.
Use internal for anything that other projects have no reason to depend on, such as implementation details of a service or helper classes. It shrinks the public surface you must keep stable and stops other teams from coupling to code you want to change freely. Exposing only deliberate entry points also reduces the number of places where unsafe usage can occur.