4 real time use of Partial classes and partial methods.

Introduction

Recently I was hunting about partial classes and the real time use of the same. Many of those postings found on google talked about the concept of partial classes and partial methods, but in what scenarios to use them very few highlighted.

In this article we will first start with fundamentals of partial classes and methods and then discuss the 4 real time use of the same.

I have also created a video of the same here where I have discussed about partial classes and shown the real time use of the same.


Fundamentals of partial classes

A partial class allows a single class to be divided in to two separate physical files. During compile time these files get compiled in to single class. For instance you can see in the below figure we have the customer class divided in to two different files “customer1.cs” and “customer2.cs”.

During compilation these files gets compiled in to single class internally. So when you create an object of the customer class you will be able to see methods lying in both the physical files. For instance you can see “Add” method belongs to “customer1.cs” and “Delete” method belongs to “customer2.cs” , but when the customer object is created we can see both “Add” and “Delete” methods.

par

Fundamentals of partial methods

There is one more important concept in partial classes called as partial methods. Partial methods helps us to define a method definition in one of the physical files and we can implement that method in the other physical files as shown in the below figure.

In the below figure you can see we have defined “Validate” method in “Customer1.cs” and this validate method is implemented in “Customer2.cs”. Please note the partial keywords attached to both of these methods.

par

Use number 1:- ASP.NET auto generated code

The biggest use of partial classes is in technologies where there is code generation. Microsoft team themselves use partial classes in ASP.NET, LINQ and EF code generation. For instance when we look at ASP.NET there are two parts one is the auto generated code of a page and the other is behind code where you write your custom logic.

The custom logic is written in the “.aspx.cs” file while the auto generated logic is in “.aspx.designer.cs” file as shown in the below figure.

par

As a developer you would like the auto generated code to do his work i.e. generate code when you drag and drop a button the ASP.NET designer.

par

Below is how the code snippet of the auto generated code looks like.

public partial class WebForm1 {

///
/// form1 control.
///
///
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
///
protected global::System.Web.UI.HtmlControls.HtmlForm form1;

///
/// Button1 control.
///
///
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
///
protected global::System.Web.UI.WebControls.Button Button1;

///
/// Label1 control.
///
///
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
///
protected global::System.Web.UI.WebControls.Label Label1;
}

At the same time you would also like to customize the code in some other file so that the auto generation part is not disturbed. For the same ASP.NET provides the “.aspx.cs” file which is a partial class where in you can go put your own custom logic.

public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Your custom logic
        }
    }

This is only possible when the class is split in two physical files but united via the partial keyword. So if you see any ASP.NET behind code class files it’s marked by the word partial.

So by using the partial keyword in ASP.NET the Microsoft team has made VS and developer work side by side thus not fiddling with each other’s code and thus increasing productivity.

par

Use number 2:- LINQ and Entity framework

LINQ and EF also use partial classes and methods heavily because of the auto generation nature of these technologies. So when you drag tables in these framework they create auto generated classes as shown in the below figure.

In the below figure you can see how the auto generated code has partial classes and partial methods.

par

par

The partial methods later can be extended to put custom logic. For instance you can see in the below code for the above autogenerated class “tblCustomer” we have used partial methods to override the “OnCustomerCodeChanged” event to ensure that customer code is not more than 8 length.

public partial class tblCustomer
    {
        partial void OnCustomerCodeChanged()
        {
            if (_CustomerCode.Length > 8)
            {
                throw new Exception("Customer code can not be greater than 8");
            }
        }
    }

So by using partial classes and partial methods, LINQ and EF framework keep auto generating classes and by using partial methods we can customize the class with our own logic.

Use number 3:- Better maintenance by compacting large classes

The other important use of partial classes is for better maintenance of the project. If you have large classes with lots of methods as shown in the below figure , it’s a bit pain to maintain those classes.

par

By using partial classes you can split them in to physical files as shown in the below figure thus making your project better and easy to maintain.

par

Use number 4:- Multiple people working on the same class

pal

The last and final real time I see of partial classes is when we want simultaneously two developers to work in the same class. I agree this can be a very rare use as there are better options like using a version control software like TFS or Sub version, but in case you want something quick and local this option is not bad at all.

You can also watch my 500 videos on different technologies like .NET, C#, Silverlight, Azure, VSTS, WCF, WPF, WWF,Share Point, design patterns, UML and lots more.

For other author’s blog on Most asked Dotnet interview questions articles.

Advertisements

About c# and .NET Interview questions

This blog is for developers who want to crack .NET and C# interviews. It has all tips and tricks needed to crack .NET interviews , C# interview , SQL Server interview , Java interview , WCF Interview , Silverlight interview , WPF interview , LINQ interview , Entity framework Interview. Do not forget to watch our Learn step by step video series. Learn MVC in 16 hours:- https://www.youtube.com/watch?v=Lp7nSImO5vk Learn AngularJS Step by Step:- https://www.youtube.com/watch?v=0kmdjqgO9IY Learn Design Pattern in 8 hours:- https://www.youtube.com/watch?v=YDobmucohqk Learn C# and .NET in 60 days:- https://www.youtube.com/watch?v=yh2SrzCkNQA Learn MSBI in 32 hours:- https://www.youtube.com/watch?v=mGPJx3ocFgg Learn SharePoint Step by Step in 8 hours:- https://youtu.be/C2fW76SwJNU
This entry was posted in Uncategorized and tagged , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s