Learn About Partial Class In C#

Introduction

 
Let's start with the interesting astronomical theory that some astrophysicists believe that there are multiverses. This theory is even backed by math as well.
 
Basically, a multiverse is a group of universes, just like our universe is just part of a multiverse group. Multiverse & Astronomy are pretty interesting topics in themselves. But today we are going to learn a similar concept in C#.
 
In C# there is the concept of partial classes. Let's say we have one class named Earth. In the multiple universe theory, every universe will have their own earth. That means the earth is present at different spaces at the same time.
 
The same way in C#, one class can be presented at different locations, but still can be treated as one single class by the compiler. Such classes are known as partial classes.
 
Basically, I can have one class in multiple files and it will get compiled at the same time.
 
Note
We first need to understand that the file name and class name are 2 different things. The file name can be different from the class it contains & one file can have multiple classes or interfaces, enums for that matter.
 
Let's try to have 1 class in 3 different files. See the image for reference:
 
The Logical View
 
 
The Actual View
 
 
First, create new a class named PlanetEarth. File name & class name will be the same.
 
File name : PlanetEarth.cs : defind Earth's properties.
  1. namespace LeranCSharp.Entities  
  2. {  
  3.     public partial class PlanetEarth  
  4.     {  
  5.         public string Volume { getset; }  
  6.         public string Mass { getset; }  
  7.         public string Age { getset; }  
  8.     }  

  • This class has 3 properties. which defines Earth.
  • It is decorated by Partial keyword, which tells the compiler, that this is just one part of PlanetEarth, there may be other classes with same name exist.
Same Namespace  
I want you to bring close attention to the namespace. There are 2 folders: 1. BusinessLogic, 2. Entities.
 
Let's create a new class in BusinessLogic's folder,
 
File Name: PrintEarthProperties.cs : prints Earth's properties.
 
  • Even though this newly created class was partial, still compiler was unable to find it relative partial class hence this class was unable to access properties that we created in Entities PlanetEarth's class.
  • There is one rule, All partial class must have the same namespace.
  • Let's change the namespace to namespace to LeranCSharp.Entities & try again. we don't need to move the class out of the folder just replace the namespace.
    1. namespace LeranCSharp.Entities    
    2. {    
    3.     partial class PlanetEarth    
    4.     {    
    5.         public void DisplayProperties()    
    6.         {    
    7.             System.Console.WriteLine("Volume: "+ Volume + " Mass: "+ Mass + " Age: "+ Age);    
    8.         }    
    9.     }    
    10. }    
  • Now the compiler can allow this class is to access properties such as Volume, Mass & Age. Even if they are not actually present in this file. That's the answer to our mystery. Because it is a partial class, it can access the properties and methods of the same partial classes from different files.
  • More than 2 Partial classes
Can we have more than 2 instances of one partial class? Of course we can.
 
Let's create a new file named SolarSystemPlacementEarth.cs : Tells us why Earth is a habitable zone. 
  1. namespace LeranCSharp.Entities  
  2. {  
  3.     partial class PlanetEarth  
  4.     {  
  5.         public void HabitableZone()  
  6.         {  
  7.             System.Console.WriteLine("Earth is positioned within the habitable zone of the solar system at 92,957,130 miles," +  
  8.                 " making Earth unique within this solar system. This zone is defined as the distance from the sun where water can be found in solid and liquid form." +  
  9.                 " If Earth were in Mercury or Venus' position, its atmosphere and water would evaporate." +  
  10.                 " If Earth were pushed out to the position of Mars or further out near the gas giants, " +  
  11.                 " it would be too cold to sustain liquid water or life." +  
  12.                 "Credits: https://sciencing.com/six-properties-earth-8371705.html");  
  13.         }  
  14.     }  

Let's call our PlanetEarth from main method,
  1. using LeranCSharp.Entities;  
  2. using System;  
  3.   
  4. namespace LeranCSharp  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             PlanetEarth earth = new PlanetEarth()  
  11.             {  
  12.                 Volume = "1.08321×1012 km3 (2.59876×1011 cu mi)",  
  13.                 Mass = "5.97237×1024 kg (1.31668×1025 lb) (3.0×10−6 M☉)",  
  14.                 Age = "4.543 billion year's old"  
  15.             };  
  16.             earth.DisplayProperties();  
  17.             earth.HabitableZone();  
  18.   
  19.         }  
  20.     }  
  21. }   
 
It worked.. The compiler didn't have any difficulties compiling this partial class.
  •  Key Points

    • We can use partial keyword with class, interface, method.
    • Partial classes must share the same namespace. So they should be available in the same assembly.
    • All partial classes must have the same access modifiers. Or compiler will throw the following error:
        1. Error   CS0262  Partial declarations of 'PlanetEarth' have conflicting accessibility modifiers 
  • Using keywords such as static, sealed on any instance of the partial class will be applicable to all the respective instances. 
What is the real purpose behind the partial class
 
Say we are using entity framework as ORM tool, right. And we have some POCO classes, say student.
  1. public class Student  
  2. {  
  3.     public int StudentID { getset; }  
  4.     public string StudentName { getset; }  
  5.     public DateTime? DateOfBirth { getset; }  
  6.     public string Grade { getset; }  
  7. }   
  • In order to keep code clean & understandable, we should not touch poco class for anything other than it's Entity framework's features. Now we have a partial class for doing so.

    • For example, if I wanted to calculate grades of a student, I will not touch the student entity rather I will simply create a new class StudentBusinessLogic and just add logic for calculating grades in that specific class.

  • The advantage of such architecture is one can simply read database related properties from one without getting it confused with all other business logic.

Conclusion

  • We learned what is a partial class
  • How to use a partial class
  • Best practice to use partial classes
  • And a bit of astronomy as well.
Thank you all for being here, I hope this small piece of information was helpful enough.
 
All the best to all of you.