Question

Sorry for the genericness of the title, I really don't understand the error that I'm receiving.

So I'm following this tutorial on C#, and I'm up to the section "Structs & Memory Management".

Around the 5:30 mark, he begins creating a Color Struct, so I follow along, line for line. All the while, his code shows no errors.

My Errors

Mine does, however. Four of them, to be precise:

1) Error 1: Backing field for automatically implemented property 'Color.R' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.

Errors 2 & 3 are the same as 1, except replace Color.R with Color.G & Color.B.

Finally, error 4:

The 'this' object cannot be used before all of its fields are assigned to.

Code

Here's my code for my Color struct (again, I'm struggling to notice any difference between my code and the tutorial master's code):

public struct Color
{
    public byte R { get; private set; }
    public byte G { get; private set; }
    public byte B { get; private set; }

    public Color(byte red, byte green, byte blue)
    {
        R = red;
        G = green;
        B = blue;
    }

    public static Color Red
    {
        get { return new Color(255, 0, 0); }
    }

    public static Color Green
    {
        get { return new Color(0, 255, 0); }
    }

    public static Color Blue
    {
        get { return new Color(0, 0, 255); }
    }

    public static Color Black
    {
        get { return new Color(0, 0, 0); }
    }

    public static Color White
    {
        get { return new Color(255, 255, 255); }
    }
}

I'm totally new to C#, but have some PHP experience, so I'm a little confused as to what exactly is happening here. Thoughts?

Was it helpful?

Solution

Structs can only really use the default constructor to be built initially. Change your constructor to call the default:

public Color(byte red, byte green, byte blue)
    : this() 
{
    this.R = red;
    this.G = green;
    this.B = blue;
}

By calling this you are using the default constructor and then setting the private values on that particular instance. If this was a class instead of a struct your code would have worked without issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top