Search code examples
c#delegatesclass-diagram

initialized delegates in class diagram


I use Visual Studio 2015, and I have created a class diagram to have an overview of my most-used classes and their members.

I have a delegate defined in a class named UserMessage:

public delegate void ProcessUserMessage(UserMessage message);

I use this delegate in an other class:

public UserMessage.ProcessUserMessage ProcessUserMessage;

So far no problems.

Because I hate testing the callback for null every time, I hook up a no-op event handler at initialization, as suggested here:

public UserMessage.ProcessUserMessage ProcessUserMessage = delegate { };

But when I do that, and re-open the class diagram, it fails to load, saying:

Code could not be found for one or more shapes in class diagram 'ClassDiagram1.cd'. Do you want to attempt to automatically repair the class diagram?

The auto-repair doesn't work of course ;-(

Even when I place this initiatlization in the class' constructor, instead of at the declaration, the same error appears.

I fail to understand what's wrong. Any clues?


Update: I created a blank project with just the failing code:

public partial class MainWindow
{
    public UserMessage.ProcessUserMessageDelegate ProcessUserMessage = delegate { };
}

public class UserMessage
{
    public delegate void ProcessUserMessageDelegate(string foo);
}

The strange thing is that the class diagram for MainWindow loads fine, but for UserMessage it fails. But I am not changing anythign for UserMessage.

It loads OK if I change class MainWindow to:

public partial class MainWindow
{
    public UserMessage.ProcessUserMessageDelegate ProcessUserMessage;
}

Solution

  • Found the solution...

    The anonymous no-op delegate must conform to the delegate definition, so all I had to add was add the argument ((string foo) in this example):

    public partial class MainWindow
    {
        public UserMessage.ProcessUserMessageDelegate ProcessUserMessage = delegate (string foo){ };
    }
    
    public class UserMessage
    {
        public delegate void ProcessUserMessageDelegate(string foo);
    }