Open In App

Partial Methods in C#

Improve
Improve
Like Article
Like
Save
Share
Report

C# contains a special method is known as a partial method, which contains declaration part in one partial class and definition part in another partial class or may contain both declaration and definition in the same partial class.
Basically, partial methods exist in the partial class, or in the struct. A partial method may or may not contain implementation if a partial method doesn’t contain an implementation in any part then the compiler will not create that method in the final class or driver class. A partial method is declared with the help of the partial keyword as shown below.

Syntax:

partial void method_name
{
    // Code
}

Important Points:

  • The declaration of the partial method must begin with partial modifier.
  • The partial method may contain ref.
  • The partial method does not contain out parameters.
  • It is implicitly private method.
  • It can be a static method.
  • Partial method is generic.
  • It can have only void return type.
  • A partial method is created only in partial class or in partial struct.

Example: We have a class named as Circle. The functionality of the Circle class is chopped into two different files named as circle1.cs and circle2.cs. These circle1.cs and circle2.cs files contain the partial class of the Circle class and partial method, i.e area. The circle1.cs file contains the declaration of the partial area() method and circle2.cs file contains the implementation of the area method as shown below:

circle1.cs




public partial class Circle {
  
    // This file only contains
    // declaration of partial method
    partial void area(int p);
  
    public void Display()
    {
        Console.WriteLine("Example of partial method");
    }
}


circle2.cs




public partial class Circle {
  
    public void newarea(int a)
    {
        area(int a);
    }
  
    // This is the definition of
    // partial method
    partial void area(int r)
    {
        int A = 3.14 * r * r;
        Console.WriteLine("Area is : {0}", A);
    }
}


When we execute the above code, then compiler combines circle1.cs and circle2.cs into a single file, i.e. circle as shown below.

circle




public class Circle {
  
    public void Display()
    {
        Console.WriteLine("Example of partial method");
    }
  
    public void newarea(int a)
    {
        area(int a);
    }
  
    private void area(int r)
    {
        int A = 3.14 * r * r;
        Console.WriteLine("Area is : {0}", A);
    }
}




Last Updated : 23 Jan, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads