Pages

Search

Monday, April 9, 2012

Partial Class and Method


Declaring a class as “partial” enables the developer to extend the capabilities of class to add extra members with in by creating the same partial class in an another file.

Ex:-
I can create below class in “Class1.cs”
  public partial class Class1
    {
        public void Method1()
        {
            Console.WriteLine("Hello this is method1");
        }
    }
I can also create a class with same name (Class1) as below, in “Class2.cs”, which means I am trying to add functions to an existing partial class.
  public partial class Class1
    {
        public void Method2()
        {
            Console.WriteLine("Hello this is method2");
        }
    }
Similarly, partial methods can be declared in a partial class and can be implemented in the specific partial class. Below example demonstrates the same.

Program.cs
    public partial class MyClass1
    {
        public void Met1()
        {
            Console.WriteLine("Method 1");
            Met2();
        }
         partial void Met2();
    }

MyClass.cs

  public partial class MyClass1
    {
        partial void Met2()
        {
            Console.WriteLine("Method 2");
        }
    }

Now when I create instance for “MyClass1” and invoke “Met1”, “Met1” when calls “Met2” it calls the implemented function in specific partial class.
Note: Partial methods cannot be declared with access specifiers and also cannot be invoked from the object of the class directly which in turn can be called in an another function(s).



No comments:

Post a Comment