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
First, create new a class named PlanetEarth. File name & class name will be the same.
File name : PlanetEarth.cs : defind Earth's properties.
- namespace LeranCSharp.Entities
- {
- public partial class PlanetEarth
- {
- public string Volume { get; set; }
- public string Mass { get; set; }
- public string Age { get; set; }
- }
- }
- 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.
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.
- namespace LeranCSharp.Entities
- {
- partial class PlanetEarth
- {
- public void DisplayProperties()
- {
- System.Console.WriteLine("Volume: "+ Volume + " Mass: "+ Mass + " Age: "+ Age);
- }
- }
- }
- 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.
- namespace LeranCSharp.Entities
- {
- partial class PlanetEarth
- {
- public void HabitableZone()
- {
- System.Console.WriteLine("Earth is positioned within the habitable zone of the solar system at 92,957,130 miles," +
- " 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." +
- " If Earth were in Mercury or Venus' position, its atmosphere and water would evaporate." +
- " If Earth were pushed out to the position of Mars or further out near the gas giants, " +
- " it would be too cold to sustain liquid water or life." +
- "Credits: https://sciencing.com/six-properties-earth-8371705.html");
- }
- }
- }
Let's call our PlanetEarth from main method,
- using LeranCSharp.Entities;
- using System;
-
- namespace LeranCSharp
- {
- class Program
- {
- static void Main(string[] args)
- {
- PlanetEarth earth = new PlanetEarth()
- {
- Volume = "1.08321×1012 km3 (2.59876×1011 cu mi)",
- Mass = "5.97237×1024 kg (1.31668×1025 lb) (3.0×10−6 M☉)",
- Age = "4.543 billion year's old"
- };
- earth.DisplayProperties();
- earth.HabitableZone();
-
- }
- }
- }
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:
-
- 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.
- public class Student
- {
- public int StudentID { get; set; }
- public string StudentName { get; set; }
- public DateTime? DateOfBirth { get; set; }
- public string Grade { get; set; }
- }
- 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.