The C# Partial Class
• C# 1.1 requires you to put all the code for a class in a single file
• C# 2.0 allows you to split the definition and implementation of a class or a
struct across multiple files. You can put one part of a class in one file and
another part of the class in a different file, noting the split by using the new
partial keyword
* Normally Partial Classes are classes that can be defined at more than one
location, but which contain different members.
* Partial Classes also allow you to store the same class, with different members, in
different physical locations.
using System;
using System.Collections.Generic;
using System.Text;
namespace PartialClassExample
{
public partial class class1
{
public void fn1()
{
Console.WriteLine("Hi");
}
}
public partial class class1
{
public void fn2()
{
Console.WriteLine("Hello");
}
}
public partial class class1
{
public void fn3()
{
Console.WriteLine("Bye");
}
}
public class myclass
{
static void Main(string[] ar)
{
class1 ob = new class1();
ob.fn1();
ob.fn2();
ob.fn3();
}
}
}
• Partial type support is available for classes, structures, and interfaces, but you
cannot have a partial enum definition.
• ASP.NET 2.0 uses partial classes for the code-beside class (the evolution of
codebehind), storing the machine-generated part of the page separately.
• Windows® Forms uses partial classes to store the visual designer output of the
InitializeComponent method as well as the member controls.
• Partial types also enable two or more developers to work on the same type while
both have their files checked out from source control without interfering with
each other.
• C# 2.0 supports partial types as follows: when the compiler builds the assembly,
it combines from the various files the parts of a type and compiles them into a
single type in Microsoft intermediate language (MSIL). The generated MSIL has no
recollection which part came from which file. Just like in C# 1.1 the MSIL has no
record of which file was used to define which type.
• Also worth noting is that partial types cannot span assemblies, and that a type
can refuse to have other parts by omitting the partial qualifier from its
definition.
Note: Classname should be the same in different files
changes made to the file will be lost if you regenerate the wrapper class. Using a partial class, you can factor those changes into a separate file.
About Partial Classes in C#
Subscribe to:
Post Comments (Atom)



0 comments:
Post a Comment