Partial Classes In C#

We discussed about classes in our earlier posts and I am assuming that you know fairly about classes by now. Now we will be discussing a different type of class that is, partial class. It's name reveals a bit about it which says partial i.e not complete. Let's see what it is and why partial class is useful?

partial class in csharp .net





What Is A Partial Class?


In C# we have various keywords that signify some unique .Net features. One such feature is to split a class into two or more physical files which will be automatically combined into one single file after compilation. 
To do this we have partial keyword. It is used to declare a partial class as shown below


//First part of partial class
public partial class School
{
    public void CountStudents()
    {
    }
}
//Second part of partial class
public partial class School
{
    public void CountTeachers()
    {
    }
}


//It will be compiled as one class as below
public class School
{
    public void CountStudents()
    {
    }

    public void CountTeachers()
    {
    }
}


Why We Need Partial Class?


There are times when splitting up the files help and partial classes become desirable.
  • When we have large projects then splitting up the files help multiple programmers to code simultaneously over different physical files.
  • You can segregate different sections of a class if the file is big enough and has multiple functionalities.
  • When you work with windows forms, visual studio generates two separate files for you. One is NewForm.designer.cs and other is plain NewForm.cs file. You can notice a partial keyword written there.

How To Use Partial Class?


To make a class partial all you need to have is partial keyword, as shown in above example where partial keyword is written before class keyword and that's it. You can make as many partial classes as you want but there are few per-requisites:

  • Partial keyword is to be used in each part of partial class.
  • All parts of the partial class should be inside the same namespace.
  • Physical file name can be different but class name should be same for all the partial classes that we want to be compiled as one class.
  • Each part of a partial class should have same accessibility.
  • If you inherit a class or interface on a partial class, then it is inherited on all parts of a partial class.

So that's all about partial classes. However things don't end here. There are few other types of classes that we haven't touched yet and will be covered in next posts. Stay tuned. 

Happy Learning!! Follow our full C# Tutorial Index for complete series.


Comments

Popular posts from this blog

Create Android Apps - Getting Started

Kotlin Type Checking and Smart Cast with Examples