Sunday, June 1, 2008

partial class [C# ASP.NET VS2005]

Partial class allow us to separate definition of one class in separate file, but it behave like usual class, u can call a function that define in other partial class.
So what the use of it?
  • when the size of the file is getting bigger, it is harder to maintain, so one of the way is to split classes base on its functionality.
  • it will allow programmers to add some definition of the class simultaneously
  • when working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when creating Windows Forms, Web Service wrapper code, and so on. You can create code that uses these classes without having to edit the file created by Visual Studio.
class definition without partial class, for example we save the code in Company.cs
using System;
using System.Collections.Generic;
using System.Text;
public class Company
{
static void Main(string[] args)
{
ITDepartment a = new ITDepartment();
HRDepartment b = new HRDepartment();
Console.ReadLine();
}

private class ITDepartment
{
public ITDepartment()
{
Console.WriteLine(”itdepartment”);
}
}

private class HRDepartment
{
public HRDepartment()
{
Console.WriteLine(”hrdepartment”);
}
}
}
we can break down the code into several files
Company.cs
using System;
using System.Collections.Generic;
using System.Text;

public partial class Company
{
static void Main(string[] args)
{
ITDepartment a = new ITDepartment();
HRDepartment b = new HRDepartment();
Console.ReadLine();
}
}
Company.HRDepartment.cs
using System;
using System.Collections.Generic;
using System.Text;

public partial class Company
{
private class HRDepartment
{
public HRDepartment()
{
Console.WriteLine("hrdepartment");
}
}
}
Company.ITDepartment.cs
using System;
using System.Collections.Generic;
using System.Text;

public partial class Company
{
private class ITDepartment
{
public ITDepartment()
{
Console.WriteLine("itdepartment");
}
}
}
Kindly refer to this tutorial for other reference

No comments: