C# - Basics - Classes - Partial Classes
Ocak 10, 2011 by C# Tutorial
|
|
Partial Classes
This topic contains and tries to cover following subjects:
- Explanation of Partial Classes in C#
- An example of Using Partial Class in C# with basic console application example
#Explanation of Partial Classes
In a C# Class, the source code can be divided into another files (CS files) with partial keyword. For example, There is a Class named "CL_notebook", and have two field within. It is as follows:
Above Class code is a usual approach. Partial Keyword steps in here, allows a Class to be divided into another files. General Idea behind is to enable programmer-developers to work on a big Class entity with separating same Class into different files, into the parts.
#Example of Partial Classes
Our example may not fit to reflect that idea without having a big Class, but we will divide two fields of our Class into another files to demonstrate how Partial Class works to show it simplier: To make a Class Partial in C#. Example contains following steps:
- Created a console Application
- Added Class which had been demonstrated at earlier screenshot
- Added two Class file in Visual Studio ("notebookClass_part1.cs","notebookClass_part1.cs"): those files will be containing our partial Class parts.
- Created an object in main method of console application to verify the the availability of both fields
of our Class.
Following console application is created.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NS_hardwareManagerApp
{
class CL_notebooks
{
public string field_notebookID;
public string field_notebookName;
}
class CL_x
{
static void Main(string [] args)
{
CL_notebooks o_aNotebook = new CL_notebooks();
}
}
}
Two Class file (CS file "notebookClass_part1.cs" and "notebookClass_part1.cs" into the console application project. Screenshot demonstrates.
In both Class file, same Class has been added with partial keyword preceding the Class name. 1th file contains one field of Class, 2nd another. Source code screenshot of both files which Class has been divided with Partial keyword:
1th file:
2nd file:
When it is tried to be accessed the fields of Class Object-Instance, Visual Studio indicates that both fields are available even they have been added into different files. Following screenshot indicates availability of both fields:
As it is indicated by last image, both field members are available from Class, even the Class has been divided into another files with another CS file names.
Note: both CS file namespace s need to be same apart from Class name. Otherwise, VS considers the Classes as different.
Data Layers
Area: | programming \ Languages \ csharp \ \ \ |
Ref: | http://msdn.microsoft.com/en-us/library/wa80x488%28v=VS.80%29.aspx |
Loc: | articles |
Tags: | csharp |
|