Partial Methods in C# 3.0 and VB.net 9.0

Partial methods are a new language feature in both VB.net and C# and are designed to enable lightweight event handling and hooks into the class.  The code samples are in C#, but I have provided a link at the bottom for the VB.net version – the principals are the same.

Few important points:

  • Partial methods can only be defined or implemented within a partial class.
  • They must return void however can accept arguments (ref parameters but not out parameters).
  • Must be private

Consider the following C# code which has a simple getter and setter for the name of a person.

partial class Person
{
        string name;

        public string Name
        {
            get { return name; }

            set
            {
                OnNameChanging(value);
                name = value;
                OnNameChanged();
            }
        }

        partial void OnNameChanging(string name);

        partial void OnNameChanged();

}

When a name is set, a call is made to the OnNameChanging method, passing in the value as a parameter. After the name has changed the OnNameChanged method is called.  But these methods are just placeholders/interfaces which could be implemented by a developer.

In a separate partial class we can then implement this functionality which will handle what we want to happen when the methods are called.

partial class Person
{
        partial void OnNameChanged()
        {
            Console.WriteLine(“OnNameChanged()”);
        }

        partial void OnNameChanging(string name)
        {
            Console.WriteLine(“OnNameChanging(string name)”);
            Console.WriteLine(name);
        }
}

Now, when we compile, everything will be merged and act as a single class. If we then set the name on the object, the following is wrote out to the console

OnNameChanging(string name)
Ben Hall
OnNameChanged()

But what what happens if no partial class implements the method body for a partial method? Well, the compiler removes calling reference from the code and does not get compiled. If the two methods where not implemented, the setter would look like this:

set
{
  name = value;
}

The result is that it is really effective to include calls to partial methods within generated code, like from a Linq DataContext, because if they are not taken advantage of then they are removed.

Looking forward to seeing how these will be used.

Links

C# Sample | VB.net Sample

http://blogs.msdn.com/wesdyer/archive/2007/05/23/in-case-you-haven-t-heard.aspx
http://blogs.msdn.com/vbteam/archive/2007/03/27/partial-methods.aspx

Technorati Tags: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *