Tuesday, December 15, 2009

C# 3.0, properties.

After discovering that my favourite game platform could potentially use C# 3.0, I decided to see what I might be missing out on while I'm stuck with C# 2.0. I found the relevant document on MSDN, and came across this curious snippet. It is an example of "Automatically Implemented Properties".

public Class Point {
public int X { get; set; }
public int Y { get; set; }
}


Please enlighten me C# experts, why would I want do this? Surely this is semantically equivalent to:

public Class Point {
public int X;
public int Y;
}


It seems all the first snippet does is add extra function call overhead and extra keyboard taps. What am I missing here?

4 comments:

LogicalError said...

Some code works trough reflection and could possibly require properties, so that's one reason.
Another is that you can do
public int myProperty { get; private set; }
which basically makes your variable read-only from the outside of your class.
All in all it's not much more than syntactic sugar and I wouldn't be surprised if the JIT compiler optimizes it away (at least I -hope- so)

Nick said...

I've hardly used C#, but I generally feel that having properties accessed via methods allows for greater flexibility.

Here are a couple of examples:

1) Subclasses could perform additional processing whenever the properties are accessed.

2) Assuming that run-time method delegation is possible for instances, an event could be triggered whenever a property in a particular instance is modified.

In the above examples, additional functionality can be added without polluting the base class or system code-base (since it can be added via subclasses or directly input into interpreter).

As LogicalError mentioned, a good JIT should optimise away any performance difference. However, it looks like the programmer still has the option of enforcing a "standard" property without function calls.

Again, I've hardly used C#, so I don't know if there are other mechanisms to more easily achieve the above - but it looks fairly sound to me.

Greg said...

As I understand it, it's so you can replace the getter or setter implementation later on if you need to.

To me, this is just further evidence that get and set are evil. If there's any possibility that the implementation might change, then a) you should call it through an interface rather than as a raw class method, and b) you just shouldn't name it/write it as get or set in the first place.

dowlingw said...

Imagine the situation where you have a Class whose underlying storage or operation changes in a major way.

It might be that those values are calculated or require parsing before storing in the new underlying storage, etc.

In either case you can abstract this detail away without changing the interface.

Popular Posts