Wednesday, January 10, 2007

* CSharp Tip #3 : .NET Partial Types

.NET languages now support distributed definition of classes which means a single class can be defined at multiples places/files and gets compiled into one during compilation. The keyword used to implement this feature is partial.

Consider the following code :

using System;
using System.Collections.Generic;
using System.Text;

namespace VikasGoyal.PartialClass
    class Program
        static void Main(string[] args)
            Console.WriteLine(Math.subtract(3, 2));
    partial class Math
        public static double add(double num1, double num2)
        { return num1 + num2; }
    partial class Math
        public static double subtract(double num1, double num2)
        { return num1 - num2; }

The class definition of Math has been distributed into two but at compile time it gets aggregated into one and the client for the class sees it as a single class. The definition can be distributed to multiple files also. This feature provides advantage mainly in two scenarios :

1. In large projects separating a class over multiple files allows multiple programmers to work simultaneously.

2. When the code is generated the generated class can be enhanced without touching the generated code. This simplifies the maintenance.

Partial keyword works on class, struct and interface definitions but its not available on delegate or enumeration declarations. The following of types are merged at compile time :

* XML Comments

* interfaces

* generic-type parameter attributes

* class attributes

* members

 Partial types can make a significant contributions in designing classes if properly used.

No comments:

Post a Comment