Struct Constructor Initialisation
I’m working on a personal project atm (more details to come in another post), and needed to use a Point to represent points on a 2D plane, with floating-point accuracy. The Point struct itself works on ints, and i need more precision than that, so i went ahead and created my own AccuratePoint struct.
1: public struct AccuratePoint
2: {
3: public AccuratePoint(Single x, Single y)
4: {
5: this.X = x;
6: this.Y = y;
7: }
8:
9: public Single X { get; set; }
10: public Single Y { get; set; }
11: }
Note the use of C# 3.0’s automatically implemented properties. Very neat little feature and saves writing boilerplate code. Try to compile, and it fails with:
Backing field for automatically implemented property must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer
Seems odd. It’s telling me that because i’m using the auto-implemented properties, i need to call the default constructor as an initialiser, like this:
1: public AccuratePoint(Single x, Single y) : this()
If i fully-implement the properties myself, i don’t need to call the initialiser.
1: public struct AccuratePoint
2: {
3: public AccuratePoint(Single x, Single y)
4: {
5: this._x = x;
6: this._y = y;
7: }
8:
9: Single _x, _y;
10: public Single X { get { return _x; } set { _x = value; } }
11: public Single Y { get { return _y; } set { _y = value; } }
12: }
Which was something i didn’t know about structs – ie: you can’t set values on public properties in the constructor without calling the initialiser first. You can set the value of private fields, but in the case of an autogenerated property, you don’t have access to the private field because it’s created by the compiler….So the moral of the story is that if you’re using autogenerated properties and setting their value in the constructor of a struct, you need to call the initialiser first.
Learnt something new.
EDIT:
I just discovered System.Drawing.PointF….oh well….i’ve now learnt two new things
Related posts:
- Thread Safety and Locking I was recently reading a post about writing non-threadsafe code...
- A Programming Job Interview Challenge #14 – 2D Geometry Well I could tell a lie and say that I...
- Strongly-Typing Your Domain Values I love this one. I don’t know the name of...
- Managing Multiple Git Accounts I’m in a situation where I want to keep different...
- Relocating Your Windows Profile To A Different Location In the last few OS rebuilds of my machine, i’ve...
Is it a game? It’s a game isn’t it. Unless it’s some sort of plotting/graphing software, but then you are a boring, boring person.
No, sadly it’s not a game.
Yes, it is being used for plotting, but it’s not *that* boring either