C# Public Properties vs. Java getX() and setX()
Martin Fowler blogged about C# properties a couple weeks back saying that he “.. liked the notion of properties right from the start..” because it’s “.. much more natural to write obj.X = other.X.” Further, ” … from a language point of view, properties and fields look the same. So if I have a field x which I can just read and write to, I can just declare it as a field. I don’t worry about this violating encapsulation, because should I wish to do something more fancy I can just replace it with a property later. It all saves a lot of typing of stupid accessor functions.” For those of you who have never used C#, instead of writing this in Java:
// Java getter & setter
private String foo;
public String getFoo() {
return this.foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
// access the private variable foo like this:
bar = obj.getFoo();
you can write this:
// C# public property
private String _foo;
public String Foo {
get { return _foo; }
set { _foo = value; }
}
// access the private variable _foo like this:
bar = obj.Foo;
I initially liked this feature of C# as well, it definitely seems more natural to use properties. Also, like Martin mentions, it saves you from having to make decisions about encapsulation.. do you use a getX()/setX() method or do I just mark it as public? With C#, you can change the implementation without changing your published API.
Martin points out that in this case beauty is only skin deep. If you use reflection to access the public properties or fields of a C# class, you might be surprised to see that the implementation does in fact change. In the example above, the property ‘Foo’ gets turned into 2 methods: get_Foo() and set_Foo(), which you can see using reflection:
Type type = (typeof(YourClassName));
MemberInfo [] members;
members = type.GetMembers(BindingFlags.Public|BindingFlags.Instance);
Console.WriteLine( “\nThe public instance members of class ‘{0}’ are : \n”, type);
for (int i =0 ; i
Martin ends by noting “… now I have to write stupid accessor functions for accessible data values.” which is something that your IDE can do for you. In Eclipse, declare your private instance variables and then right click –> Source –> Generate Getter & Setter…
9 Comments