Since Visual Basic 2008 and the .NET Framework 3.5, you can take advantage of another interesting feature that has been included in Visual Basic 2010: partial methods. Basically this feature has been mainly introduced in LINQ to ADO.NET, but it can be used in different scenarios for other language features. The concept behind partial methods is the same as partial classes: Methods implementations can be split across multiple parts. Partial methods have three particular characteristics: They must be Private
methods, they cannot return values (that is, only Sub
methods are allowed), and their bodies must be empty in the class in which methods are defined. Consider the following code, in which a class named Contact
is split across partial classes and a partial method is defined:
A partial method is marked with the Partial
keyword. It has a Private
scope, returns no value, and its definition’s body is empty. Suppose you want to implement the actual code for your method. For example, we could verify if the Email
address provided by the user is a valid address; to accomplish this, we can use regular expressions.
Regular expressions are an advanced way to work with text. The .NET Framework provides the System.Text.RegularExpression
namespace that exposes classes for managing regular expressions with .NET languages.
The following code shows how you can implement a partial class in which the actual code for a partial method is provided:
When you effectively implement the partial method, you do not need to mark it again as Partial
. This qualifier must be added only in the empty method definition. The preceding code checks if the specified email address is valid; if it is not, it throws an InvalidOperationException
.
Partial methods are mentioned when discussing LINQ to SQL so that you can get an overview of practical implementations of partial methods, which are particularly useful when you need to provide custom validation techniques.
To describe partial methods in another way, the concept is “to accomplish this particular task, you do need this particular method. But the implementation of the method is left to your choice.”
3.147.53.166