Sie sind auf Seite 1von 10

12.

5M

(23K on)

Sign in

articles Q&A forums Lounge

Search for articles, questions, tips

Partial Classes in C# With Real Example


Sandeep Singh Shekhawat, 29 Dec 2014

CPOL

Rate this:

4.73 (61 votes)

I explain partial classes in C# language with an example

Introduction
In this article, I explain partial classes in C# language with an example. A partial class
splits the definition of a class over two or more source files. You can create a class
definition in multiple files but it will be compiled as one class.
Suppose you have a "Person" class. That definition is divided into the two source files
"Person1.cs" and "Person2.cs". Then these two files have a class that is a partial class.
You compile the source code, then create a single class. Let's see that in Figure 1.1.

Figure 1.1 : Partial class and compiled class

Advantages of a Partial Class


Here is a list of some of the advantages of partial classes:
1. You can separate UI design code and business logic code so that it is easy to read
and understand. For example, you are developing a web application using Visual
Studio and add a new web form then there are two source files, "aspx.cs" and
"aspx.designer.cs". These two files have the same class with the partial keyword.
The ".aspx.cs" class has the business logic code while "aspx.designer.cs" has user
interface control definition.
2. When working with automatically generated source, the code can be added to the
class without having to recreate the source file. For example, you are working with
LINQ to SQL and create a DBML file. Now when you drag and drop a table, it creates a
partial class in designer.cs and all table columns have properties in the class. You
need more columns in this table to bind on the UI grid but you don't want to add a
new column to the database table so you can create a separate source file for this
class that has a new property for that column and it will be a partial class. So that
does affect the mapping between database table and DBML entity but you can easily
get an extra field. It means you can write the code on your own without messing with
the system generated code.
3. More than one developer can simultaneously write the code for the class.
4. You can maintain your application better by compacting large classes. Suppose you
have a class that has multiple interfaces so you can create multiple source files
depending on interface implements. It is easy to understand and maintain an
interface implemented on which the source file has a partial class. Let's see the
following code snippet.
Hide Copy Code

public interface IRegister


{
//Register related function
}
public interface ILogin
{
//Login related function
}

//UserRegister.cs file
public partial classUser : IRegister, ILogin
{
//implements IRegister interface
}
//UserLogin.cs file
public partial classUser
{
//implements ILogin interface
}

Points That You Should be Careful about Partial Classes


There are some points that you should be careful about when you are developing a
partial class in your application.
1. You need to use partial keyword in each part of partial class.
2. The name of each part of partial class should be the same but source file name for
each part of partial class can be different.
3. All parts of a partial class should be in the same namespace.
4. Each part of a partial class should be in the same assembly or DLL, in other words
you can't create a partial class in source files of a different class library project.
5. Each part of a partial class has the same accessibility.
6. If you inherit a class or interface on a partial class, then it is inherited on all parts of
a partial class.
7. If a part of a partial class is sealed, then the entire class will be sealed.
8. If a part of partial class is abstract, then the entire class will be an abstract class.

Using the Code


I will develop an example that explains how to use a partial class in your project.
Suppose you are working with LINQ to SQL in your application. So you create a data
context, in other words a .dbml file and drag and drop the necessary tables. Each table
creates a partial class in the data context designer file and each table field becomes a
property for the table. Suppose you have a "Person" table that has the three fields
"Id","Name" and "DateOfBirth" and you want to show the age of each person in a grid view.
What will you do? If you add a new column to the table for age in database for the "Person"
table then it fails the normalization rule so you should not do that. If you add a new
property to auto-generated code, then it will not be mapped to the database. So you need
to create a partial class portion in a separate source file that has the "Age" property. This
"Age" property calculates the age of the person when you bind a person list to the grid
view. Let's see each step-by-step.
1. Create a "Person" table in the database.
You need to create a person table in the database that has the three fields "Id","Name"
and "DateOfBirth". The "Id" field is the primary key.
Hide Copy Code

CREATE TABLE Person


(
Id int identity(1,1)primary key,
Name nvarchar(50),
DateOfBirthDate default getUtcDate()
)

2. Create a web application from Visual Studio.

3. Right-click on the project in the Solution Explorer, then go to "Add" and click on
"Class".
4. Choose "LINQ to SQL Classes" from the list and provide the name "Person" for the
DBML name. Then click on "Add".
5. Drag the User table from the database in the Server Explorer and drop onto the O/R
Designer surface of the "Person.dbml" file.

Figure 1.2: Person entity


Now you can open the "Person.designer.cs" file. In the file, the "Person" partial class
has been created for drag and drops a "Person" table from database on O/RM
surface.
6. Create a partial class part that has the "Age" property to calculate the age. This file
is named "PersonExtension.cs".
Hide Copy Code

using System;
namespace PartialClassExample
{
public partial class Person
{
public int Age
{
get { return Convert.ToInt32(System.DateTime.UtcNow.Date.Year _DateOfBirth.Value.Year); }
}
}
}

7. Create a UI design to show a person's details in the grid view.


Hide Copy Code

<%@Page Language="C#"AutoEventWireup="true"
CodeBehind="PersonUI.aspx.cs"Inherits="PartialClassExample.PersonUI"%>
<!DOCTYPEhtml>
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"runat="server">
<title></title>
</head>
<body>
<formid="form1"runat="server">
<div>
<asp:GridViewID="gridPerson"runat="server">
</asp:GridView>

</div>
</form>
</body>
</html>

8. Write code for the "Page_Load" event to bind a grid view by person list in the code
behind file.
Hide Shrink

Copy Code

using System;
using System.Linq;
namespace PartialClassExample
{
public partial class PersonUI : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (PersonDataContext context =new PersonDataContext())
{
var query = from person in context.GetTable<person>()
select new
{
person.Id,
person.Name,
person.DateOfBirth,
person.Age
};
var content = query.ToList();
gridPerson.DataSource = content;
gridPerson.DataBind();
}
}
}
}</person>

9. Run the application, you will see the Age column in the grid view that shows the age
of each person. Let's see that in Figure 1.3.

Figure 1.3: Output

License
This article, along with any associated source code and files, is licensed under The Code

Project Open License (CPOL)

Share
EMAIL

TWITTER

About the Author

Sandeep Singh Shekhawat


Software Developer

India
Sandeep Singh Shekhawat is a Software Developer. He is awarded for C# Corner
MVP(2013,2014 and 2015) and CodeProject MVP (2015). His three articles at
CodeProject are prize wining in article competition. His more than 10 articles has been
selected Article of the Day at Microsoft ASP.NET (http://www.asp.net/) community.

You may also be interested in...


Four real world uses of Partial classes and Partial
methods

Real-Life Examples of how IBM DB2 with BLU


Acceleration is Creating Value for Enterprises

A Real Polynomial Class with Root Finder

SAPrefs - Netscape-like Preferences Dialog

Real World OCR

Generate and add keyword variations using


AdWords API

Comments and Discussions

You must Sign In to use this message board.


Search

Go

First Prev Next

Excellent & Informative Article


VR Karthikeyan

14-Mar-16 18:24

Consistency in an Example
Member 12133631

good

anilh.chavan

13-Nov-15 10:38

3-Feb-15 0:49

Re: good

Sandeep Singh Shekhawat

3-Feb-15 17:29

Can you extend Classes across two separate Libraries?


reeselmiller2

31-Dec-14 7:58

thank

Member 10149906

30-Dec-14 13:10

Re: thank

Sandeep Singh Shekhawat

30-Dec-14 17:24

My vote of 1
Nam1222

30-Dec-14 12:42

Re: My vote of 1
icemanind

31-Dec-14 7:21

Re: My vote of 1
Nam1222

16-Jan-15 21:05

Re: My vote of 1
icemanind

17-Jan-15 5:52

Re: My vote of 1
Nam1222

17-Jan-15 13:10

Re: My vote of 1
icemanind

18-Jan-15 11:06

Re: My vote of 1
Mario Z

Good

chargoy

24-May-16 23:37

30-Dec-14 5:39

My vote of 5

Humayun Kabir Mamun

My vote of 2

Member 11290173

29-Dec-14 22:19

26-Dec-14 0:30

Re: My vote of 2

Sandeep Singh Shekhawat

1 Question

Member 10334156

26-Dec-14 1:25

22-Nov-14 1:24

Re: 1 Question

Sandeep Singh Shekhawat

22-Nov-14 15:47

Re: 1 Question
PIEBALDconsult

30-Dec-14 4:44

Re: 1 Question

Sandeep Singh Shekhawat

30-Dec-14 4:49

Re: 1 Question
PIEBALDconsult

30-Dec-14 5:44

Re: 1 Question
Antonio Ripa

31-Dec-14 1:54

Tutorial is very clear


Member 11191614

29-Oct-14 19:38

Re: Tutorial is very clear


Sandeep Singh Shekhawat

My vote of 3

Klaus Luedenscheidt

22-Nov-14 15:48

13-Sep-14 18:06

Re: My vote of 3

Sandeep Singh Shekhawat

14-Sep-14 4:08

Re: My vote of 3
reeselmiller2

29-Dec-14 20:31

Re: My vote of 3
PIEBALDconsult

30-Dec-14 17:16

Re: My vote of 3
Klaus Luedenscheidt

Thoughts

PIEBALDconsult

30-Dec-14 18:27

13-Sep-14 4:55

Re: Thoughts
CS2011

16-Sep-14 4:17

Good Job

Member 10879623

28-Jul-14 18:40

Re: Good Job

Sandeep Singh Shekhawat

30-Aug-14 16:44

Message Automatically Removed


31-Mar-14 23:49

My vote of 5
Mihai MOGA

14-Feb-14 17:05

Re: My vote of 5

Sandeep Singh Shekhawat

30-Aug-14 16:45

My vote of 5
ThatsAlok

10-Feb-14 1:49

Re: My vote of 5

Sandeep Singh Shekhawat

10-Feb-14 2:13

good work
winnervijay

7-Feb-14 6:42

Re: good work

Sandeep Singh Shekhawat

30-Aug-14 16:43

Can u provide detail steps for the coding?


yuzaihuan

23-Jan-14 16:37

Re: Can u provide detail steps for the coding?


Sandeep Singh Shekhawat

30-Aug-14 16:46

Sandeep Singh Shekhawat

30-Aug-14 16:46

My vote of 1
Antonio Ripa

14-Jan-14 4:37

Re: My vote of 1
PIEBALDconsult

30-Dec-14 4:46

Re: My vote of 1
Antonio Ripa

31-Dec-14 2:01

Re: My vote of 1
PIEBALDconsult

31-Dec-14 4:41

Re: My vote of 1
Antonio Ripa

31-Dec-14 6:40

Re: My vote of 1
PIEBALDconsult

31-Dec-14 6:46

Refresh
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160904.1 | Last Updated 29 Dec 2014

1 2 Next
Article Copyright 2014 by Sandeep Singh Shekhawat
Everything else Copyright CodeProject, 1999-2016

Das könnte Ihnen auch gefallen