Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why prefer Properties to public variables? [duplicate]

Tags:

syntax

c#

Other being able to sanity check values in a setter is there a more underlying reason to prefer properties to public variables?

like image 930
PaulB Avatar asked Apr 10 '09 10:04

PaulB


People also ask

Why we use properties instead of public variables?

Use of properties makes your code more object oriented. By making member variables public, you are exposing your implementation. Save this answer.

Why use public variables?

You can use public variables as a shortcut to avoid the need to provide getters and setters, but there is no need to do so, and because there is a negative consequence (increased coupling to the internal design of the class) I would suggest that sacrificing design for brevity in this way is not often a good idea.

Are properties faster than fields C#?

Bobb, Microsoft knows very well that no matter how much they trumpet design philosophy/shmilosophy, everybody would use public fields instead of properties once they realize that it's whooping 34% faster (even though it's a micro-optimization in 99.9% of the cases, people would do it anyway).

Why do we use properties in C#?

Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code. A get property accessor is used to return the property value, and a set property accessor is used to assign a new value.


1 Answers

We've had this subject before but I can't find anything now.

In brief: your needs might change: where there's no sanity check now, one might be required in the future. However, if you change your public fields to properties, this breaks binary compatiblity: every client who uses your code/library would have to re-compile.

This is bad because it potentially costs a lot of money.

Using properties from the beginning avoids this problem. This even counts for code that is not part of a library. Why? Because you never know: the code (even if highly domain-specific!) might prove useful so you want to refactor it to a library. This refactoring process is obviously made much easier if you are already using properties in place of public/protected fields.

Additionally, writing public properties is easy in C# 3.0 because you can just use the auto-implemented properties, saving you quite a bit of code:

public DataType MyProperty { get; set; }

Will implement the necessary backing field and getter/setter code for you.

I will add a personal note: .NET's behaviour in this regard is somewhat lazy. The compiler could just change public fields to properties on the fly, thus avoiding the problem. VB6 already did this for COM-exposed classes and I see absolutely no reason for VB.NET and C# not to do the same. Perhaps someone on the compiler teams (Jared?) could comment on this.

like image 151
Konrad Rudolph Avatar answered Oct 11 '22 20:10

Konrad Rudolph