C# Partial Class With Example

Let’s see a example First . Create three files first

File1.cs

/*File1.cs*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PartialClasses
{
    class File1
    {
    }
    public partial class Record
    {
        private int h;
        private int w;
        public Record(int h, int w)
        {
            this.h = h;
            this.w = w;
        }
    }
}

File2.cs

/*File2.cs*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PartialClasses
{
    class File2
    {
    }
    public partial class Record
    {
        public void PrintRecord()
        {
            Console.WriteLine("Height:" + h);
            Console.WriteLine("Weight:" + w);
        }
    }
}

Program.cs

/*Program.cs */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PartialClasses
{
    class Program
    {
        static void Main(string[] args)
        {
            Record myRecord = new Record(10, 15);
            myRecord.PrintRecord();
            Console.ReadLine();
        }
    }
}

What is Partial Class

Partial Class is a way by which we can split the functionality of a particular class into multiple class files and all these files will be combined into one single class file when the application is compiled.

What is the necessity of Partial Class

While working on large scale projects, multiple developers want to work on the same class file at the same time. To solve this problem, c# provides an ability to spread the functionality of a particular class into multiple class files .

How Partial Class Working / Working Principle of Partial Class

Using the partial keyword we can split the definition of a particular class, structure, interface or a method over two or more source files.

Above is the example of splitting the definition of Program class into two class files, File2.cs and File1.cs.

Rules to Implement Partial Class:

  1. All parts of partial type definitions must be in the same namespace or assembly. Check the example..
  2. All parts of partial type definitions must have the same accessibility, such as public, private, etc.
  3. If any partial part is declared as abstract, sealed or base, then the whole type is considered as abstract or sealed or base based on the defined type.
  4. In c#, different parts can have different base types but the final type will inherit all the base types.
  5. Nested partial types are allowed in partial type definitions.
  6. The partial modifier can only appear immediately before the keywords class, struct or interface.