I thought I knew C#

I honestly thought I had a pretty fair grasp on C# for the last few years.

But apparently there are features that I haven’t known about.

The first one is covariance on arrays in C#

string[] strings = new[]{"Hello","Covariance"};

//assign the string array to an object array
object[] objects = strings; 

objects[0] = "Hi"; //OK
objects[1] = 123; //runtime exception

I know that true covariance and contravariance will come in C# 4.

But I really didn’t know it was already implemented for arrays, I found this out maybe two months ago.

Also note the last line, we got dynamic type checks in C# , ewwww ;-)

Another feature I didn’t know about is this:

this = new Foo();

Think I’m kidding with you?

Assignments to “this” ??

This is actually possible inside structs, which makes sense when you think about it, since you only overwrite the memory for the struct.

But I honestly didn’t know this was possible until I saw the Tuple struct in MEF a few days ago.

Maybe this is common knowledge, but if someone had told me that you could assign values to “this” in C# before I saw that, I would have slapped him.

//Roger

2 thoughts on “I thought I knew C#”

  1. This covariance thing on arrays is really a CLR thing. The CLR inserts the dynamic type checks at machine code level.

    I agree. This is actually tricky. Such a thing won’t get noticed in a code review. Who would expect the following code to throw an ArrayTypeMismatchException?

    void Change(object[] array)
    {
    array.Requires(“array”)
    .IsLongerThan(0);

    array[0] = 5;
    }

  2. CLR Arrays are covariant to allow J# to run existing Java code, as Java arrays are covariant, and have to be for java generics, etc so if they wanted the CLR to be able to run (basically) unmodified Java they needed this.

    It makes me cry a little inside though.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s