Stuff that's in my head

Can open... Worms? everywhere! The blog of Colin Angus Mackay
posts - 379, comments - 486, trackbacks - 51

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.

Print | posted on Monday, March 23, 2009 12:11 AM

Feedback

Gravatar

# re: I guess I've never needed to do this before...

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-c

It appears just calling through with initialization to this() will fix it.
4/8/2009 3:24 PM | Dale Thompson

Post Comment

Title  
Name  
Email
Url
Comment   

Powered by: