bwall
bwall

Reputation: 1060

Does C# generate separate methods when you use a Generic Parameter with constraints?

I want to implement a WPF function that can raise events on a wide variety of things - from Hyperlinks to Buttons. Both a hyperlink and a button are DependencyObjects that implement IInputElement.

I wrote this function:

private void DoStuff<T>(T element, RoutedEvent anEvent) where T : DependencyObject, IInputElement
{
     element.RaiseEvent(anEvent);
}

This works great, but made me wonder if my code would generate a new method for labels, buttons, contentcontrols, hyperlinks, and anything else that I passed into it? Do you know? It seems like that would be a waste of resources in this case because my method does the same thing to all of them.

I found lots of helpful references on how to constrain generic methods, but not much on code generation. I believe C++ does generate entire new classes when using generics, but wasn't sure about C#.

Upvotes: 1

Views: 47

Answers (1)

Yennefer
Yennefer

Reputation: 6234

The method definition is compiled in MSIL only once. You can verify the claim by dumping the IL, indeed, this is the designed behaviour because you describe what you want: a method with placeholders.

However, at runtime, things get more difficult: the JIT compiler will emit as many copies as necessary of your generic each time with different object size.

Keep in mind that these are implementation details and are subject to change across versions.

In particular, reference types share the same method as they inner runtime class is the same, while each value types get their own method.

The link posted in the comments, for example, gives you an insight of the process.

Upvotes: 1

Related Questions