#637 – A Delegate Can Refer to A Partial Method

You can have a delegate refer to a partial method, but only if the partial method is implemented.  At compile-time, if a delegate points to a partial method and you’re compiling only the declaration of the partial method, but not an implementation, you’ll get a compiler error.

    // Dog-1.cs
    public partial class Dog
    {
        // Action is a delegate type in System that takes
        //   no parameters and returns a void
        Action barkDelegate;

        public Dog()
        {
            // Point delegate to partial method Bark.
            barkDelegate = Bark;
        }

        public void BarkViaDelegate()
        {
            barkDelegate();
        }

        // Partial method declaration--no implementation here
        partial void Bark();
    }
    // Dog-2.cs
    public partial class Dog
    {
        // Implementation of Bark
        partial void Bark()
        {
            Console.WriteLine("Woof!");
        }
    }
        static void Main()
        {
            Dog d = new Dog();
            d.BarkViaDelegate();
        }

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: