A partial class in c# can be used to split functionality across multiple files, each with the same namespace and name.
A good use case for them is to use them as a stepping-stone in refactoring god-classes. If a class has multiple responsibilities (really large files), it may be a TEMPORAL way to refactor & split behaviours, before splitting them into different classes.
Usually, you can’t have 2 classes with the same name. This is unless you mark them as partial.
// this works fine, although it's not the best use case
public partial class MyClass
{
public bool Ok { get; set; }
}
public partial class MyClass
{
public bool IsOk()
{
return Ok;
}
}
When you have multiple partial classes the compiler will merge them all into one single class.
Some rules:
- access modifiers must be the same
- you can only inherit one class; you can implement multiples interfaces
- constructors must have different signatures
Reference(s)
https://www.roundthecode.com/dotnet-tutorials/what-are-partial-classes-csharp-why-do-we-use-them#:~:text=A%20partial%20class%20can%20be,file%20with%20a%20MyClass%20class.
https://stackoverflow.com/questions/3601901/when-is-it-appropriate-to-use-c-sharp-partial-classes