C#.NET - What's a Partial Class?

jdana
jdana used Ask the Experts™
on
Here's a basic question.  What's a partial class?
Partial-Class.png
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015
Commented:
It is a class that is split into one or more "partial" definitions. These classes are combined into one class during compilation. Take a look at a Forms project's code. The form is split into a "code-behind" class and a "designer" class. The designer (the place where drag/drop controls) automatically overwrites the .designer.cs file any time you make a change to the design surface. If you didn't have these files split, then any time you made a change, your code (i.e. the logic you write in your code-behind) would be overwritten as well.

The partial definitions of the class may be all in the same file, or they may be split amongst many files.
Commented:
In other words: it helps you organize your class-code a little by splitting your code in different files.
F.e.:
you have a large class that has some thousand lines of code. You have 300 lines of code for different constructors, 1000 lines for properties that are accessible from outside and 2000 lines of code for class internal methods.
That would make 3300 lines of code what is a lot for a single class and it makes handling the code a little confusing. You could use #region areas to show / hide some parts of the class or you can use partial class-concept that allows you to store the lines of code of your class in different (physical) files.

you can have something like in the attached code (just a sample).
 
//mySuperclass.contructors.cs
public partial class mySuperClass
{
  public mySuperClass()
 {...}
 public mySuperClass(int a)
 {...}
 public mySuperClass(string s)
 {...}
}

//mySuperclass.props.cs
public partial class mySuperClass
{
  public int IntVal{ get; set;}

  public string StringVa {get;set;}
}

//mySuperclass.methods.cs
public partial class mySuperClass
{
  private void DoSomething()
  {...}

   private string DoSomethingElse(int a, int b)
  {...}
}

Open in new window


In the end it is still one class and is treated like that by the compiler and visual studio while developing. There is no difference in using it.

Author

Commented:
Thanks!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial