What’s wrong with C#: Properties
Friday, September 12th, 2003Me>C# is just java with (often poorly thought out) additions
Zohar >Interesting. Which additions do you consider poorly thought out?
Well here’s one: Properties.
C# says:
public Foo Foo
{
set {this.foo = value;}
get {return foo;}
}
...
someFoo = Foo;
where java would say
public Foo getFoo() {return foo;}
public void setFoo(Foo foo) {this.foo = foo;}
...
someFoo = getFoo();
So what?
Well here’s some reasons I dislike this:
1. It is impossible in C# to have a setter at a different protection level to the getter. If you want a protected setter, you need to define a protected Foo SetFoo(Foo foo). Kind of defeats the purpose.
2. It is impossible in C# to overload a setter. This means that you can’t have what in java world would be good practice:
public void setFoo(Foo foo) {this.foo = foo;}
public void setFoo(MyFooLikeThing fooLikeThing) {
setFoo(fooLikeThing.asFoo());
}
You can of course still do this sort of thing in C#, but it is not overloading — the developer needs to know that x.Foo = foo and x.SetFoo(fooLikeThing) are the same thing. Two different syntaxes for the same operation does not aid easy comprehension or code readability.
3. In java it is clear if you do a = x.foo that you are not doing a function call and no side effect can happen. In C# a = x.Foo may be a simple getter or may instantiate a remote webservice. I can never know. And so I will assume the worst and comprimise my design to allow for the possibility that the get might do something expensive.
4. For some reason (probably to do at least partly with the limitations I mentioned above) the .NET libraries seem ambivalent on properties. Quite often you see x.GetFoo() where you might expect to see a property. the immediate questions are “Why is this not a property? What secret machinations are happening that means that it is not a prroperty? Should I treat this method differently to a true property?”. Truth is its probably just happenstance and the way the team felt on the day - but that doesn’t help me make a decision on how to use the method.
5. public Foo Foo {get;} — Come on! What were they thinking! Java’s Foo foo; is bad enough! At least there the case gives you a clue!
Of course all of the above is aesthetic. But that is what language is about — aesthetics and ease of comprehension.







