A lot of the discussion about .NET 4.0 is revolving around the introduction of co-variance and contra-variance for generic types.

It’s important to remember, though, that these concepts aren’t entirely new - there has been some support for variance built into .NET for some time.

For example, consider this snippet of code:

    public Form1()
    {
        InitializeComponent();
        textBox1.KeyPress += Handler;
        button1.Click += Handler;
        textBox1.KeyPress += new KeyPressEventHandler(Handler);
        button1.Click += new EventHandler(Handler);
    }

    private void Handler(object sender, EventArgs e)
    {
        label1.Visible = true;
    }

You can see here the Handler() method being registered for both the TextBox.KeyPress event and the Button.Click event, even though these events have different parameters (Button.Click expects parameters object and EventArgs while TextBox.KeyPress expects object and KeyPressEventArgs).

What’s going on?

Without specific compiler support, this wouldn’t work. But, variance comes into play. The compiler recognises that the second parameter of Handler() is of type EventArgs - which is sufficiently general to accept any possible value that might be supplied by the event. Based on this observation, the compiler hooks up the event without complaint.

Comments

blog comments powered by Disqus
Next Post
TechEd New Zealand 2009  19 Sep 2009
Prior Post
Coming up to speed  10 Sep 2009
Related Posts
Convention testing for immutable types  30 Nov 2019
Modifying Words, Part the Second  16 Nov 2019
Modifying Words, Part the First  09 Nov 2019
Hashcodes  26 Oct 2019
Code Gardening  19 Oct 2019
Nullable types redux  12 Oct 2019
C# 8 and .NET Core 3.0  28 Sep 2019
Commands and CommandBinding  21 Sep 2019
Debugging word selection  14 Sep 2019
ViewModel Subscriptions  31 Aug 2019
More csharp posts »
Archives
September 2009
2009