Sunday, June 2, 2013

Partial class Modifier

Partial class modifiers are used to define a single class across multiple files, this modifier is useful when we want to write large and complex classes. Splitting the class across multiple files improves the readability of the class and improves maintainability.

In the following example we shall define a single class in 2 files by adding the modifier partial to the class, create an instance of the partial class and invoke the methods which are defined in both the files.
File: ParticalClass1.cs

    partial class PartialClass
    {
        public void PartialClassMember1()
        {
            Console.WriteLine("From file PartialClass1.cs");
        }
    }


File: ParticalClass2.cs
    partial class PartialClass
    {
        public void PartialClassMember2()
        {
            Console.WriteLine("From file PartialClass2.cs");
        }
    }

Now we can create an instance of the class ParticalClass and invoke the members defined in both the files as follows.

    PartialClass objPartialClass = new PartialClass();
    //
    objPartialClass.PartialClassMember1();
    objPartialClass.PartialClassMember2();

When the above code executes the output will be as follows.

From file PartialClass1.cs
From file PartialClass2.cs

Notice that the methods from both the files get executed and the output is printed.

Search Flipkart Products:
Flipkart.com

No comments: