What are Partial Methods In C#?
Ready has the concept of partial classes in C#, but I never knew that we can also have Partial Methods. Yes, we can have Partial Methods in C#. This concept also uses the Partial keyword but there are some restrictions/guidelines with the use of the Partial Methods.
public partial class ClassA
{
public void SetSalary()
{
SetData();
// Perform other functionality here
}
partial void SetData()
{
Console.Write("This is a partial method.");
Console.ReadKey();
}
}
Here is a list of attributes of a partial method.
- A partial method can only be created in partial classes or partial structs.
- In order to create a partial method, it must be declared first(like an abstract method), with a signature only and no definition. After it is declared, its body can be defined in the same component or a different component of the partial class/struct .
- A partial method is implicitly private. It cannot have any other access modifier.
- A partial method can only have a void return type.
Let's see how we can create a partial method. We start by creating a partial class ClassA and add a partial method declaration.
public partial class ClassA
{
partial void GetData();
}
Now, create the second component of the partial class ClassA and add the implementation of the partial method.
public partial class ClassA
{
partial void SetData()
{
// Perform functionality here
}
}
In order to test the partial method, we add another method and call this private method inside this newly created method.
class Program
{
static void Main(string[] args)
{
ClassA cls = new ClassA();
cls.SetSalary();
}
}
public partial class ClassA
{
partial void SetData();
}
public partial class ClassA
{
public void SetSalary()
{
SetData();
// Perform other functionality here
}
partial void SetData()
{
Console.Write("This is a partial method.");
Console.ReadKey();
}
}
class Program
{
static void Main(string[] args)
{
ClassA cls = new ClassA();
cls.SetSalary();
}
}
public partial class ClassA
{
partial void SetData();
}
public partial class ClassA
{
public void SetSalary()
{
SetData();
// Perform other functionality here
}
partial void SetData()
{
Console.Write("This is a partial method.");
Console.ReadKey();
}
}
Run the code and see the result. I hope you enjoyed reading it. Happy coding.
Next. Partial Classes in C#