Wednesday 10 April 2013

Example of partial class

Partial class are allow to define a single class into multiple files (more than one class with same name), when compilation time theses classes are combined to form a single class.

The partial modifier can only appear immediately before the keywords class, struct, or interface.
More than one developer can simultaneously write the code for the partial class in big project.

Example of partial class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


/// <summary>
///example of partial class
/// </summary>

public partial class x
{
    int i, j;
    public x(int a, int b)
    {
        i = a;
        j = b;
    }
}
public partial class x
{
    public int add()
    {
        return i + j;
    }
}
public partial class x
{
    public int sub()
    {
        return i - j;
    }
}

c# code:
 protected void Page_Load(object sender, EventArgs e)
    {

        x a = new x(10, 5);
        Response.Write(a.add().ToString() +"<br>"+a.sub().ToString());

    }
out put
15
5
example of partial class with inheritance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


/// <summary>
///example of partial class
/// </summary>

public partial class x
{
  protected  int i, j;
    public x(int a, int b)
    {
        i = a;
        j = b;
    }
}
public partial class x
{
    public int add()
    {
        return i + j;
    }
}
public partial class x
{
    public int sub()
    {
        return i - j;
    }
}
public class y : x
{
    public y(int a, int b)
        : base(a, b)
    { }
    public int mul()
    {
       return i * j;
    }
}
c# code:
  protected void Page_Load(object sender, EventArgs e)
    {
        y a = new y(50, 30);
        Response.Write(a.add().ToString() +"<br>"+a.sub().ToString()+"<br>"+a.mul().ToString());

    }
OUTPUT
 80
20
150

You can also use in structure and  interface.

partial interface IA
{
    int add();
}

partial interface IA
{
    int sub();
}

partial struct SB
{
  public  int add (int i,int j)
   {
      return i+j;
   }
}

partial struct SB
{
     public  int sub(int i,int j)
   {
      return i-j;
   }

}

No comments:

Post a Comment