Junior
What are partial classes?
sobes.tech AI
Answer from AI
Partial classes in C# allow defining a single class across multiple physical source code files. This is useful for separating generated code from handwritten code, as well as when working in a team, enabling multiple developers to work on the same class simultaneously.
Key points:
- All parts must be marked with the
partialkeyword. - All parts must have the same access modifier (e.g.,
public,internal). - Parts can contain fields, properties, methods, events, nested types.
- During compilation, all parts are combined into one class.
Example usage:
File 1: MyClassPart1.cs
// Definition of the first part of the class
public partial class MyClass
{
public int MyProperty { get; set; }
public void Method1()
{
// Method 1 logic
}
}
File 2: MyClassPart2.cs
// Definition of the second part of the class
public partial class MyClass
{
public string MyField;
public void Method2()
{
// Method 2 logic
}
}
In this case, the MyClass class will contain both the property MyProperty, the field MyField, and the methods Method1() and Method2().