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.

1 Comment

  1. I just Googled your issue and found a that there is a posting on stackoverflow about this issue:http://stackoverflow.com/questions/272153/why-is-it-necessary-to-call-this-on-a-struct-to-use-automatic-properties-in-cIt appears just calling through with initialization to this() will fix it.

Leave a Comment

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 )

Connecting to %s