Partial Class:
Partial class is a keyword which is used
to split the defiition of the class into multiple parts with same singature. When complier compiles the
class file ,it makes into single file.
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 thepartial 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.
Points That You
Should be Careful about Partial Classes
1. There are some
points that you should be careful about when you are developing
a partial class in your application.
2. You need to
use partial keyword in each part of partial class.
3. The name of
each part of partial class should be the same but source file name
for each part ofpartial class can be different.
4. All parts of
a partial class should be in the same namespace.
5. Each part of
a partial class should be in the same assembly or DLL, in other words
you can't create apartial class in source files of a different class
library project.
6. Each part of
a partial class has the same accessibility.
7. If you inherit
a class or interface on a partial class, then it is inherited on all
parts of a partialclass.
8. If a part of
a partial class is sealed, then the entire class will be sealed.
9. If a part
of partial class is abstract, then the entire class will be
an abstract class.
It is possible to
split the definition of a class or a struct, an interface or a method over two or more
source files. Each source file contains a section of the type or method
definition, and all parts are combined when the application is compiled.
There are several
situations when splitting a class definition is desirable:
- When working on large projects, spreading a class over
separate files enables multiple programmers to work on it at the same
time.
- When working with automatically generated source, code
can be added to the class without having to recreate the source file.
Visual Studio uses this approach when it creates Windows Forms, Web
service wrapper code, and so on. You can create code that uses these
classes without having to modify the file created by Visual Studio.
- To split a class definition, use the partial keyword modifier, as shown
here:
C#
public partial class Employee
{
public void DoWork()
{
}
}
public partial class Employee
{
public void GoToLunch()
{
}
}
The partial keyword
indicates that other parts of the class, struct, or interface can be defined in
the namespace. All the parts must use the partial keyword. All
the parts must be available at compile time to form the final type. All the
parts must have the same accessibility, such as public, private,
and so on.
If any part is
declared abstract, then the whole type is considered abstract. If any part is
declared sealed, then the whole type is considered sealed. If any part declares
a base type, then the whole type inherits that class.
All the parts that
specify a base class must agree, but parts that omit a base class still inherit
the base type. Parts can specify different base interfaces, and the final type
implements all the interfaces listed by all the partial declarations. Any
class, struct, or interface members declared in a partial definition are
available to all the other parts. The final type is the combination of all the
parts at compile time.
Note
|
The partial modifier
is not available on delegate or enumeration declarations.
|
The following example
shows that nested types can be partial, even if the type they are nested within
is not partial itself.
C#
class Container
{
partial class Nested
{
void Test() { }
}
partial class Nested
{
void Test2() { }
}
}
At compile time,
attributes of partial-type definitions are merged. For example, consider the
following declarations:
C#
[SerializableAttribute]
partial class Moon { }
[ObsoleteAttribute]
partial class Moon { }
They are equivalent to
the following declarations:
C#
[SerializableAttribute]
[ObsoleteAttribute]
class Moon { }
The following are
merged from all the partial-type definitions:
- XML comments
- interfaces
- generic-type parameter attributes
- class attributes
- members
For example, consider
the following declarations:
C#
partial class Earth : Planet, IRotate
{ }
partial class Earth : IRevolve { }
They are equivalent to
the following declarations:
C#
class Earth : Planet,
IRotate, IRevolve { }
There are several
rules to follow when you are working with partial class definitions:
- All partial-type definitions meant to be parts of the
same type must be modified with partial. For example, the
following class declarations generate an error:
C#
public partial class A { }
//public class A { } //
Error, must also be marked partial
- The partial modifier can only appear
immediately before the keywords class, struct, or interface.
- Nested partial types are allowed in partial-type
definitions as illustrated in the following example:
C#
partial class ClassWithNestedClass
{
partial class NestedClass { }
}
partial class ClassWithNestedClass
{
partial class NestedClass { }
}
- All partial-type definitions meant to be parts of the
same type must be defined in the same assembly and the same module (.exe
or .dll file). Partial definitions cannot span multiple modules.
- The class name and generic-type parameters must match
on all partial-type definitions. Generic types can be partial. Each
partial declaration must use the same parameter names in the same order.
- The following keywords on a partial-type definition are
optional, but if present on one partial-type definition, cannot conflict with
the keywords specified on another partial definition for the same type:
For more information, see Constraints on Type Parameters (C# Programming Guide).
In the following
example, the fields and the constructor of the class, CoOrds, are declared in one
partial class definition, and the member, PrintCoOrds,
is declared in another partial class definition.
C#
public partial class CoOrds
{
private int x;
private int y;
public CoOrds(int x, int y)
{
this.x = x;
this.y = y;
}
}
public partial class CoOrds
{
public void PrintCoOrds()
{
Console.WriteLine("CoOrds: {0},{1}",
x, y);
}
}
class TestCoOrds
{
static void Main()
{
CoOrds myCoOrds = new CoOrds(10, 15);
myCoOrds.PrintCoOrds();
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
// Output: CoOrds: 10,15
The following example
shows that you can also develop partial structs and interfaces.
C#
partial interface ITest
{
void Interface_Test();
}
partial interface ITest
{
void Interface_Test2();
}
partial struct S1
{
void Struct_Test() { }
}
partial struct S1
{
void Struct_Test2() { }
}
A partial class or
struct may contain a partial method. One part of the class contains the
signature of the method. An optional implementation may be defined in the same
part or another part. If the implementation is not supplied, then the method
and all calls to the method are removed at compile time.
Partial methods enable
the implementer of one part of a class to define a method, similar to an event.
The implementer of the other part of the class can decide whether to implement
the method or not. If the method is not implemented, then the compiler removes
the method signature and all calls to the method. The calls to the method,
including any results that would occur from evaluation of arguments in the
calls, have no effect at run time. Therefore, any code in the partial class can
freely use a partial method, even if the implementation is not supplied. No
compile-time or run-time errors will result if the method is called but not
implemented.
Partial methods are
especially useful as a way to customize generated code. They allow for a method
name and signature to be reserved, so that generated code can call the method
but the developer can decide whether to implement the method. Much like partial
classes, partial methods enable code created by a code generator and code
created by a human developer to work together without run-time costs.
A partial method
declaration consists of two parts: the definition, and the implementation.
These may be in separate parts of a partial class, or in the same part. If
there is no implementation declaration, then the compiler optimizes away both
the defining declaration and all calls to the method.
// Definition in file1.cs
partial void onNameChanged();
// Implementation in file2.cs
partial void onNameChanged()
{
// method body
}
- Partial method declarations must begin with the
contextual keyword partial and the method must return void.
- Partial methods can have ref but not out parameters.
- Partial methods are implicitly private, and therefore they cannot be virtual.
- Partial methods cannot be extern, because the presence of the body
determines whether they are defining or implementing.
- Partial methods can have static and unsafe modifiers.
- Partial methods can be generic. Constraints are put on
the defining partial method declaration, and may optionally be repeated on
the implementing one. Parameter and type parameter names do not have to be
the same in the implementing declaration as in the defining one.
- You can make a delegate to a partial method that
has been defined and implemented, but not to a partial method that has
only been defined.
No comments:
Post a Comment