C# tutorials > Core C# Fundamentals > Object-Oriented Programming (OOP) > What are partial classes and methods?
What are partial classes and methods?
Introduction to Partial Classes
partial
keyword.
Partial Class Syntax
MyClass
is defined in two separate files (or within the same file). The partial
keyword indicates that these are parts of the same class. The compiler will merge these definitions into a single MyClass
type.
public partial class MyClass
{
// Part 1: Fields and some methods
public string Name { get; set; }
}
public partial class MyClass
{
// Part 2: More methods and properties
public void DisplayName()
{
Console.WriteLine("Name: " + Name);
}
}
Introduction to Partial Methods
void
. If a partial method is declared but not implemented, the compiler removes all calls to that method, so there's no performance impact. This is useful for conditional compilation and code generation scenarios.
Partial Method Syntax
OnNameChanged
is a partial method. The first part of MyClass
declares the method. The second part optionally implements the method. If the second part doesn't exist, the call to OnNameChanged()
in the Name
property's setter is simply removed by the compiler. If the second part exists, the OnNameChanged
method will be executed when Name
is changed.
public partial class MyClass
{
// Declaration (signature) of the partial method
partial void OnNameChanged();
public string Name
{
get { return _name; }
set
{
_name = value;
OnNameChanged(); // Call to the partial method
}
}
private string _name;
}
public partial class MyClass
{
// Optional implementation of the partial method
partial void OnNameChanged()
{
Console.WriteLine("Name changed!");
}
}
Concepts Behind the Snippet
Real-Life Use Case Section: Entity Framework and Code Generation
Best Practices
Interview Tip
private
nature and void
return type restriction of partial methods.
When to use them
Memory footprint
Alternatives
Pros
Cons
FAQ
-
Can I have multiple partial classes in the same file?
Yes, you can define multiplepartial
classes with the same name within the same file. -
Can a partial class inherit from another class?
Yes, a partial class can inherit from another class. The inheritance relationship must be declared in one of the partial definitions, and it applies to the entire class. -
Can I define properties or fields in different partial class definitions?
Yes, you can define properties and fields in different parts of the partial class. The compiler will merge all members into a single class definition. -
What happens if I declare a partial method but don't implement it?
If you declare a partial method but don't provide an implementation, the compiler removes the declaration and all calls to the method. This means there's no performance impact. -
Are partial methods virtual?
No, partial methods are not virtual. They are implicitly private and are either implemented or removed by the compiler. They cannot be overridden.