wasAsked.

Partial Class — why and when would you use it?

Capgemini · Full Stack Developer · technical

Published

Year not specified · Software Engineering

Community answers

Posted by wasAsked editorial collection

A partial class lets you split the definition of one class across multiple files (or multiple parts in one file). The compiler combines all parts into a single class at compile time. // Customer.cs public partial class Customer { public int Id { get; set; } public string Name { get; set; } = ""; } // Customer.Validation.cs public partial class Customer { public bool IsValid() => !string.IsNullOrWhiteSpace(Name); } Rules - Every part must use the partial keyword, be in the same assembly and namespace, and have the same accessibility. - If any part is abstract or sealed, or declares a base class, it applies to the whole class. Interfaces declared in different parts are combined. Why and when to use it 1. Separating generated code from hand-written code (the main reason) - Tools generate one part, and you write your logic in another part that is never overwritten when the code is regenerated. - Examples: WinForms and WPF designer files (Form1.Designer.cs), EF Core Database First scaffolded entities (add custom methods in a separate partial file), gRPC and Protobuf generated classes, and source generators. 2. Source generators - Modern .NET features use partial declarations so generators can supply the implementation: [GeneratedRegex(@"^\d{6}$")] private static partial Regex PincodeRegex(); [LoggerMessage(Level = LogLevel.Information, Message = "Order {OrderId} created")] static partial void LogOrderCreated(ILogger logger, int orderId); System.Text.Json source generation with partial JsonSerializerContext classes, and CommunityToolkit.Mvvm's [ObservableProperty]. 3. Organising very large classes - Splitting a large class by concern (for example a big API client into files per resource). Use this carefully: a huge class is often a sign it should be split into several classes instead. 4. Team collaboration - Different developers working on different parts of a generated or very large class with fewer merge conflicts. Partial methods - A partial method declared in one part and optionally implemented in another. Classic partial methods (private, void, no out parameters) are removed by the compiler if not implemented — useful as hooks in generated code. Since C# 9, partial methods with accessibility modifiers or return values must be implemented (this is what source generators use). C# 13 also added partial properties and indexers, again mainly for source generators. Summary: use partial classes primarily to combine generated code with custom code safely; avoid using them to hide classes that are simply too big.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics