C#: Structs and parameters

struct MyStruct
{
	public int X { get; set; }
	public int Y { get; set; }

	public MyStruct(int x, int y)
	{
		this.X = x;
		this.Y = y;
	}
}

Will trigger an error on line 8:

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

So I thought I might fix it by assigning a value to the fields. Since we have automatic properties, let’s convert them to normal properties:

struct MyStruct
{
	private int _x = 0;
	public int X
	{
		get
		{
			return _x;
		}
		set
		{
			_x = value;
		}
	}
	private int _y = 0;
	public int Y
	{
		get
		{
			return _y;
		}
		set
		{
			_y = value;
		}
	}

	public MyStruct(int x, int y)
	{
		this.X = x;
		this.Y = y;
	}
}

Let’s press F5. Oeh noes, another error:

‘MyStruct._x’ cannot have its instance field initializers in structs

So you can’t do field initialization in a struct (apart from in a function / constructor / getter / setter).

Let’s go back to the first piece of code and make it work by adding 7 characters:

struct MyStruct
{
	public int X { get; set; }
	public int Y { get; set; }

	public MyStruct(int x, int y) : this()
	{
		this.X = x;
		this.Y = y;
	}
}

The this() initializes the struct, and in the constructor itself the struct’s vars & properties are set to their default values. It’s weird though that an int needs initialization…