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.

[HTML1]

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:

[HTML2]

If i fully-implement the properties myself, i don’t need to call the initialiser.

[HTML3]

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 :)

2 comments

  1. 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. 😛

  2. No, sadly it’s not a game.

    Yes, it is being used for plotting, but it’s not *that* boring either 😉

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>