#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();
        }

Advertisement