Software Development

I guess I've never needed to do this before…

I guess I’ve never created a struct in a while (at least in Visual Studio 2008 using C# 3.0) because I’ve just discovered that the Automatic Properties don’t work in structs.

I’ve just created this struct:

public struct CapacityUnit
{
    public string Name { get; private set; }
    public long Multiplier { get; private set; }

    public CapacityUnit(string name, long multiplier)
    {
        Name = name;
        Multiplier = multiplier;
    }
}

Which at first glance looks okay except that I get a compiler error in the constructor on Name. The reason for this is that structs need to have the fields initialised before the this object can be used. Name uses this implicitly as in this.Name. So, it would seem that there is no way, at least as far as I can see, to initialise these properties when using Automatic Properties as I would need to use an implicit this.

One thought on “I guess I've never needed to do this before…

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