Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of partial classes?

Tags:

c#

.net

I read about partial classes and, for example, I understand the reason for they are used when Visual Studio creates Windows Forms, without ruling out that

when working on large projects, spreading a class over separate files enables multiple programmers to work on it at the same time

.

Later I read this example and I noticed that most of the classes are declared as partial. Why?

like image 369
enzom83 Avatar asked Feb 27 '12 23:02

enzom83


2 Answers

Partial classes allow code to not only add to the generated classes, but also implement optional functionality.

For example, there may be generated code which performs property validation (through IDataErrorInfo) but the validation on each property cannot be determined at generation time, the partial class allows the developer to specify the validation at a later point.

The generated file:

public partial class MyClass : IDataErrorInfo
{
    partial void ValidateMyProperty(ref string error);

    public string this[string propertyName]
    {
        get
        {
            string error = String.Empty;
            if (propertyName == "MyProperty")
                ValidateMyProperty(ref error);

            return error;
        }
    }

    public string Error { get { return String.Empty; } }

    public int MyProperty { get; set; }
}

The developer implemented file:

public partial class MyClass
{
    partial void ValidateMyProperty(ref string error)
    {
        if (MyProperty < 0)
            error = "MyProperty cannot be negative.";
    }
}
like image 138
Lukazoid Avatar answered Nov 08 '22 05:11

Lukazoid


One of very good examples where partial classes come useful is when the class is auto generated by a tool (like VS) and you want to be able to extend functionality of that class and do not lose your code when the tool needs to regenerate its code. For example when you use Visual Studio Entity Data Model Designer the entities (classes) will be generated as partial.

like image 18
Tomek Avatar answered Nov 08 '22 04:11

Tomek