Partial Class in C#

In this article, we will learn about partial class in C#, we will also explore the real-time use of partial class.

A partial class is a special class available in C#. It provides a way to implement the functionality of a single class into multiple classes. And, at the time of compilation, all these files are combined into a single class file.

We use partial keyword to create a partial class in C#.

Syntax of partial class:

public partial class{

}

When to use Partial class

There are multiple cases where partial classes are useful.

So, declaring a class over multiple class files allows multiple programmers to work on it at the same time.

Let’s look at some more code snippet:

public partial class Product
{
    public void StockManage()
    {
    }
}

public partial class Product
{
    public void TaxCalculation()
    {
    }
}

Here, the partial keyword indicates that we can define other parts of the class in the namespace. All the parts must have the same accessibility, such as public, private, and so on.

A real-time example of Partial Class

Let’s have a closer look at the real-time example of a partial class.

We are taking an example of Order class.

public partial class Order
{
    public int OrderId { get; set; }
    public List<OrderItem> Items { get; set; }

    public Order()
    {
        Items = new List<OrderItem>();
    }

    public void AddItem(OrderItem item)
    {
        Items.Add(item);
    }
}

Here, we have the AddItem() method and a few other properties in this class.

Next, we will add another method with some other functionalities and that too with partial class.

public partial class Order
{
    public void LogOrderCreation()
    {
        // Implement logic to log order creation details (e.g., OrderId, timestamp)
        Console.WriteLine($"Order created: {OrderId}");
    }
}

Finally, we will create the object of the Order class and then will call the method one by one.

Order myOrder = new Order();
myOrder.AddItem(new OrderItem { ProductId = 1, Quantity = 2 });
myOrder.LogOrderCreation();

Advantages of using Partial Class

Let’s look at various advantages of partial class in C#.

Partial classes allow programmers to work on the same class at the same time. Also, it helps us to maintain our application code in a more precise way.

Limitations of Partial Class

With the below rules or limitations, we can implement partial class.

  • All the definitions of the partial class must be in the same namespace.
  • We should use the same access specifier for all the parts of the partial class.

Conclusion

In this article, we learnt about Partial Classes in C#. We also know the advantages and limitations of a partial class.

Keep following: SharePointCafe.NET

Leave a Comment

RSS
YouTube
YouTube
Instagram