Enter your email address:


feedburner count

C# 2.0 : Partial types

Labels:

What is Partial types ?
Partial types is types that allow classes, structs, and interfaces to be broken into multiple pieces stored in different source files for easier development and maintenance. Additionally, partial types allow separation of machine-generated and user-written parts of types so that it is easier to augment code generated by a tool.

Problems
While it is good programming practice to maintain all source code for a type in a single file, sometimes a type becomes large enough that this is an impractical constraint. Furthermore, programmers often use source code generators (such as CodeSmith) to produce the initial structure of an application, and then modify the resulting code. Unfortunately, when source code is emitted again sometime in the future, existing modifications are overwritten.

Solution
A new type modifier, partial, is used when defining a type in multiple parts. The following is an example of a partial class that is implemented in two parts.

Part one :
public partial class Customer
{
private int id;
private string name;
private string address;
private List<Order> orders;

public Customer()
{
}
}

Part two :
public partial class Customer
{
public void SubmitOrder(Order order)
{
orders.Add(order);
}
public bool HasOutstandingOrders()
{
return orders.Count > 0;
}
}
When the two parts above are compiled together, the resulting code is the same as if the class had been written as a single unit:
public class Customer
{
private int id;
private string name;
private string address;
private List<Order> orders;

public Customer()
{
}

public void SubmitOrder(Order order)
{
orders.Add(order);
}

public bool HasOutstandingOrders()
{
return orders.Count > 0;
}
}




blog comments powered by Disqus