Is that structurally sound?

I don’t know. You spent a lot of time mastering the oddities of the struct types in the C# world, carefully preparing yourself for the subtle copying that happens when you call through an interface, and then a blog post turns up that shows that the behaviour when you call a method on a struct depends on whether it is held in a readonly field or not.

interface IInc
{
    void Increment();
}

struct TestStruct : IInc
{
    public int count;
    public void Increment()
    {
        count++;
    }
}

Defining a field of the appropriate type, we see 0,1,2 is printed by the following

TestStruct struct1;

((IInc)struct1).Increment();
Console.WriteLine(struct1.count);
struct1.Increment();
Console.WriteLine(struct1.count);
struct1.Increment();
Console.WriteLine(struct1.count);

The first value printed is zero because the call via the cast boxes the structure and hence copies it before the call mutates it.

The shocking behaviour is what happens if you change the field declaration to

readonly TestStruct struct1;

when the output changes to 0,0,0.

Simon’s blog post explains it and also links to Eric Lippert’s explanation.

Advertisements
This entry was posted in Computers and Internet. Bookmark the permalink.

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