0

I found someone with the exact same issue I had in this question, but I remain curious: why exactly does this happen? The answers to that question all said to move the offending function into its own library, which is what I did, but none of them explain why this problem occurs.

In my case, I have a class named ControlExtensions that has several useful little functions that extend control classes such as TextBox and ComboBox. To support that, the Extensions library has a reference to System.Windows.Forms. This class is in a library named Extensions. A couple of other database-related classes use other methods from the Extensions library. They do not use Windows controls, and they do not have a System.Windows.Forms reference. They have wored well for a long time.

But I just added this to the ControlExtensions class:

public static void Invoke<TControlType>(this TControlType control, Action<TControlType> delFunction)
    where TControlType : Control
{
    if (control.InvokeRequired)
        control.Invoke(new Action(() => delFunction(control)));
    else
        delFunction(control);
}

The purpose of this is the exact same thing the poster of the linked question wanted to do. And like him, as soon as I added this to my ControlExtensions class, I got the missing reference errors.

I am going to remove this from the ControlExtensions class and put it back into its own library, but I'd very much like to understand the cause of the missing reference error the addition of this method led to.

ROBERT RICHARDSON
  • 2,077
  • 4
  • 24
  • 57
  • 1
    Not sure I understand. Doesn't `where TControlType : Control` reference a WinForm's library? – LarsTech Mar 26 '19 at 15:49
  • You are paying the extension method tax. Without a reference to System.Windows.Forms the C# compiler cannot know what types match the Control constraint so cannot know which ones can be extended. What the C# compiler does not want to do is limit candidates for an extension method to only the ones it has enough type info for. That causes extremely mystifying compile errors and runtime behavior when all that the library user did was to forget to add a reference. Notable is that hiding Invoke() calls is quite unwise, you never want to paper over a source of deadlock, race and perf bugs. – Hans Passant Mar 26 '19 at 15:55
  • Thanks very much, Hans – ROBERT RICHARDSON Mar 26 '19 at 18:15

0 Answers0