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?
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.";
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With