Over on StackOverflow, saw an interesting question that taught me something new about C# 3.0.

The question Automatic Properties and Structures Don’t Mix? asked why this code doesn’t work:

struct MyStruct
{
    public MyStruct ( int size )
    {
        this.Size = size; // <-- Compile-Time Error!
    }

    public int Size{get; set;}
}

Turns out that the solution is to properly chain the declared constructor with the default parameterless constructor:

struct MyStruct
{
    public MyStruct(int size)
        : this()   // Add this for the fix
    {
        this.Size = size; // <-- Compile-Time Error!
    }

    public int Size { get; set; }
}

Which just goes to show that taking shortcuts (like not properly chaining constructors) can turn around and bite.

Interestingly, though, the C# compiler gives you all the information you need to solve this as a part of the error messages (emphasis added):

  • error CS0188: The ‘this’ object cannot be used before all of its fields are assigned to

  • error CS0843: Backing field for automatically implemented property ‘WindowsApplicationSample.MyStruct.Size’ must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.

Someone posted another solution, taken from a Codeplex project - though in this case I think the “solution” is a problem in it’s own right … check it out.

public struct TempTuple<TFirst, TSecond>
{
    public TempTuple(TFirst first, TSecond second)
    {
        this = new TempTuple<TFirst, TSecond>(); // Kung fu!
        this.First = first;
        this.Second = second;
    }

    public TFirst First { get; private set; }

    public TSecond Second { get; private set; }
}

Look at the “Kung fu!” like - assignment to this - Yikes!

Comments

blog comments powered by Disqus
Next Post
Listening time  12 Feb 2009
Prior Post
Be A Better Developer  10 Feb 2009
Related Posts
Browsers and WSL  31 Mar 2024
Factory methods and functions  05 Mar 2023
Using Constructors  27 Feb 2023
An Inconvenient API  18 Feb 2023
Method Archetypes  11 Sep 2022
A bash puzzle, solved  02 Jul 2022
A bash puzzle  25 Jun 2022
Improve your troubleshooting by aggregating errors  11 Jun 2022
Improve your troubleshooting by wrapping errors  28 May 2022
Keep your promises  14 May 2022
Archives
February 2009
2009