What are the uses of partial class and methods in C# and why are use in C# projects?

0 votes
79 views
Ethan Karla asked 28 days ago in programming by Ethan Karla

What are the uses of partial class and methods in C# and why are use in C# projects?

1 Answer

0 votes
Ravi Vishwakarma answered 23 hours ago by Ravi Vishwakarma
C# Partial Class and method
 When we are creating a Production Level Class, then any class can have thousands of Lines of Codes. So when we define a class in a single C# file, then our file can be very big. Also, when we create a class, there are often many such codes, which can be ignored once implemented. That is, there is no need to check those codes ever again.
Therefore, in C#, there has been a provision of Contextual Keyword named Partial, using which we can split a class into more than one C# Files and keep the less modified members separate from the more modified members. You can manage and maintain the Production Class in a better way.
It is necessary to specify the partial class combination with every Partial Class. The definition of a Partial Class is the same as that of a Normal Class. The only difference is that in Partial Class an extra partial word has been used.
Syntax
     partial class Person

     {
     // Data Members
     //Methods 
    partial datatype function_name(arguments); // function prototype
     }
Example
using System;

namespace CSharpClass
{
    partial class MyClass // Declaring partial class
    {
        partial void PrintSum(int x, int y); // Declaring partial method (Prototype)
        public void Add(int x, int y)
        {
            PrintSum(x, y);
        }
    }
    partial class MyClass
    {
        partial void PrintSum(int x, int y) // Implementing partial method (Definition)
        {
            Console.WriteLine('Sum is {0}', x + y);
        }
    }
  public class Program
    {
        static void Main()
        {
            MyClass myObj = new MyClass();
            myObj.Add(15, 5);
        }
    }
}
Output:
    Sum is 20