Should you use member variables or property getter/setter? [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between a field and a property in C#?
I routinely have a need to create protected variables in my class/subclass hierarchies. However I keep seeing others implementations which use a simple get/set property instead of a variable.
Since there is no code that needs to execute in the getter or setter and since their scope is always protected, is there a difference?
protected int foo1;
// vs
protected int foo2{ get; set; }
I know the advantage of the former is you can directly initialize it with a value, but I'm wondering if there are any other things/limitations I need to be aware of.
Note: There will never be a case where there is code in the getter/setter. These are simply placeholders for internally-calculated metrics and performance is critical (even to the millisecond-level) which has me thinking the first is better as it bypasses the getter/setter completely.

The difference is that, if at a later point you need to add some logic to the getter/setter methods, the calling code won't break.

I use getters and setters for protected members unless it's read-only in which case a protected readonly will do just fine. In all honesty, unless someone is using reflection to iterate over properties it really doesn't matter - you can always switch one to the other and it will compile just fine.
Actually, come to think of it, I usually just use methods since the thing I usually want to inherit is the base behaviors, not the explicit base state.
Having lots of protected properties is honestly a code smell as it somewhat breaks encapsulation.

Related

Properties in C# advantage [duplicate]

This question already has answers here:
Properties vs. Fields: Need help grasping the uses of Properties over Fields
(12 answers)
Closed 5 years ago.
Although I understand the basic concept of properties like providing read, read-write access to private data members, I am still having a hard time understanding how it would be useful over just declaring the member as public. In what scenarios is it useful? and if it is a way to change values of private fields, how is the encapsulation still being enforced?
Kindly explain with an example or link if you can
I think there is a bit of confusion on properties vs fields, and private vs. private (vs. internal)
Fields are very much like plain variables of a class. They can be public or private.
Properties, just like fields, can also be public or private. However, while they appear to behave similar to a field, they actually behave more like functions with a particular signature (signature being setter taking one single parameter of the type of the property, and getter taking no parameters and returning that type). Because they behave like a function, whenever you set or retrieve property's value, you can run arbitrary code to fulfill the behavior (i.e. caching the value, and if cache is empty, retrieving value from somewhere).
From personal experience:
You would generally have Private data member when you do not want it to be accessed externally through another class that calls the class containing the Private data member.
Public data members are those that you can access by other classes to obtain its contents.
My opinion is that it is simply proper programming syntax. Private data members are typically those of constants that you do not wish to override once it had been set, while Public are algebraic-like variables, subject to be overridden if necessary.
A similar question has been asked at:
What is the difference between Public, Private, Protected, and Nothing?.
Cheers,
iato

What is the advantage of using auto-implemented properties with the default access, instead of using public fields? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C#: Public Fields versus Automatic Properties
Do I need to use { get; set; } with c# fields that have no special actions when getting and setting
Consider these two options:
public int Foo { get; set; }
public int Foo;
They seem to be semantically equivalent, and I believe they will even compile to the same IL. So what is the advantage of using the property? Seeing a public field makes me feel uneasy, but I can't think of any concrete advantage to using the property syntax instead. If an explicit getter and setter are required in the future, public int Foo; can be replaced by public int Foo { ... } with no other changes necessary. The best I can come up with is that the property syntax just feels better, but I can hardly use this reason to convince someone else.
What is the advantage (if any) of using the property syntax in this case?
The main advantages are:
Future-proofing your API - If you later need logic in the getter or setter, your public API doesn't change.
Data binding - Most data binding frameworks only work against Properties, not Fields.
Pros
Easy declaration
Cons
Can not set a breakpoint inside set/get
Can not have a code inside get/set
Do not working on WPF DataBinding
No concept like a default value for the property, as there is no default field behind it.
Pros and cons are strictly related to the project implementation.
Just a couple of hints, pretty sure others will add something else...
I do not believe they will compile to the same IL, as get and set for properties are actually functions on the IL level and when dealing with reflection. Here are some reasons to do it though:
Reflection!
Serialization/Deserialization only works on public properties, not public fields.
Debugging, you can set break points on a get or a set, which can help to track down when the variable is accessed, specifically if you are seeing a goofy value and you don't know where it is coming from.
The primary reason that we don't use auto-implemented properties is for those serialization mechanisms that serialize the members and not the properties (such as binary serialization for .Net remoting).
In this case, if you have two applications that compile the same class separately and exchange a serialized copy of the class, there is no guarantee that it will deserialize correctly since you can't control the names of the private members.

Fields vs Properties for private class variables [duplicate]

This question already has answers here:
Are there any reasons to use private properties in C#?
(19 answers)
Closed 9 years ago.
For private class variables, which one is preferred?
If you have a property like int limit, you want it to be:
int Limit {get; set;}
and use it inside the class, like so:
this.Limit
Is there a reason to use it or not use it? Maybe for performance reasons?
I wonder if this is a good practice.
For a private member, I only make it a property when getting and/or setting the value should cause something else to occur, like:
private int Limit
{
get
{
EnsureValue();
return this._limit;
}
}
Otherwise, fields are fine. If you need to increase their accessibility, it's already a big enough change that making it a property at that point isn't a huge deal.
Edit: as Scott reminds us in the comments, side effects in properties can often cause more pain than anything else. Don't violate Single Responsibility and limit property logic to consistent, logical operations on the value only that must be done at the gate - such as lazy loading (as in the example above), transforming an internal structure into a publicly-useful format, etc.
The only real benefit an auto-property has over a field when the accessibility is private is that you can set a breakpoint on accesses and updates of the variable. If that is important to your scenario then definitely use an auto-property. Otherwise, given there is no substantial advantage, I choose to go with the simplest construct which is a field.
I would say its good practice to use a property. If ever you had to expose the limit value and used a local member it will require more coding while if its a property it would only require a change of its modifier.
I think it's cleaner also.
Granted, since it's a private API, its an implementation detail - you can do whatever you want here. However, there is very little reason to not use a property, even for private classes. The properties get inlined away by the JIT, unless there is extra code in place, so there isn't really a performance impact.
The biggest reasons to prefer properties, IMO, are:
Consistency in your API - You'll want properties in publicly exposed APIs, so making them in the private API will make your programming exprience more consistent, which leads to less bugs due to better maintainability
Easier to convert private class to public
From my perspective, using properties in lieu of variables boils down to:
Pros
Can set a break point for debugging, as Jared mentioned,
Can cause side-effects, like Rex's EnsureValue(),
The get and set can have different access restrictions (public get, protected set),
Can be utilized in Property Editors,
Cons
Slower access, uses method calls.
Code bulk, harder to read (IMO).
More difficult to initialize, like requiring EnsureValue();
Not all of these apply to int Limit {get; set;} style properties.
The point of automatic properties is they are very quick at creating a public access to some field in your class. Now, they offer no benefit over exposing straight up fields to the outside world, other than one big one.
Your class' interface is how it communicates with the outside world. Using automatic properties over fields allows you to change the internals of your class down the road in case you need to make setting the value of that property do something or check authorization rules or something similar on the read.
The fact that you already have a property means you can change your implementation without breaking your public interface.
Therefore, if this is just a private field, an automatic property isn't really that useful, not only that, but you can't initialize public properties at declaration like you can with fields.
I generally follow the following principle: If it's for strictly private use, use a field as it is faster.
If you decide that it should become public, protected or internal some day, it's not difficult to refactor to a property anyway, and with tools like ReSharper, it takes about 3 seconds to do so... :)
There's nothing wrong with having private or protected properties; this is mostly useful when there is some rule or side effect associated with the underlying variable.
The reason why properties seem more natural for public variables is that in the public case, it is a way to hedge one's bet against future implementation changes, whereby the property will remain intact but the implementation details somehow move around (and/or some additional business rule will be needed).
On performance, this is typically insignificant, or indeed identical for straight-assignment properties.
I personally dislike (but often use) plain assignment properties because they just clutter the code. I wish C# would allow for "after the fact refactoring".
Properties provide some very good automatic features (like Json and Xml Serialization)
Fields do not.
Properties can also be a part of an Interface. If you decide to refactor later on... this might be something to consider too.
Properties are just syntactic sugar, C# will compile them into get_PropertyName and set_PropertyName, so performance differences are not a consideration.
If your data member need only set and get logic then properties are very good and fast solution in C#

Why prefer Properties to public variables? [duplicate]

This question already has answers here:
Closed 13 years ago.
Other being able to sanity check values in a setter is there a more underlying reason to prefer properties to public variables?
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.
In a nutshell:
You can control acces (readonly,
writeonly, read/write)
You can validate values when setting
a property (check for null etc)
You can do additional processing,
such as lazy initialization
You can change the underlying
implementation. For example, a
property may be backed by a member
variable now, but you can change it
to be backed by a DB row without
breaking any user code.
Jeff Atwood has blogged about it:
There are valid reasons to make a trivial property, exactly as depicted above:
Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties.
You can't databind against a variable.
Changing a variable to a property is a breaking change.
It's a shame there's so much meaningless friction between variables and properties; most of the time they do the exact same thing. Kevin Dente proposed a bit of new syntax that would give us the best of both worlds:
public property int Name;
However, if the distinction between variable and property is such an ongoing problem, I wonder if a more radical solution is in order. Couldn't we ditch variables entirely in favor of properties? Don't properties do exactly the same thing as variables, but with better granular control over visibility?
Changing a field to a property in the future is considered a breaking change. Fields are considered implementation details of classes and exposing them publicly breaks encapsulation.
Use of properties makes your code more object oriented. By making member variables public, you are exposing your implementation.
Also see this link from C#'s Programming Guide
You can also protect write access and allow read access with a property:
public int Version { get; private set; }
If you work in a closed environment -- you dont develop a SDK, all classes are used within a same project framework -- there is no difference.
The usual argument is that "in the future you may need to do some check on the values, so it is easier with properties". I dont buy it at all.
Using public fields is more readable, less decoration and easier to use.
Yes.
Consider a public varibale which now holds a string, you can simply set it. However, if you decide that that public variable should hold an object which should be initialized with a string then you would have to change all your code using your original object. But if you would have used setter you would only have to change the setter to initialize the object with the provided string.

c# using setters or getters from base class

Is it recommended to set member variables of a base class to protected, so that subclasses can access these variables? Or is it more recommended to set the member variables to private and let the subclasses get or set the varible by getters and setters?
And if it is recommended to use the getters and setters method, when are protected variables used?
This is very similar to this question, about whether to access information within the same class via properties or direct access. It's probably worth reading all those answers too.
Personally, I don't like any fields to be non-private with the occasional exception of static readonly fields with immutable values (whether const or not). To me, properties just give a better degree of encapsulation. How data is stored is an implementation decision, not an API decision (unlike properties). Why should class Foo deriving from class Bar care about the implementation of class Bar?
In short, I'd always go for properties, and I don't use protected variables for anything other than throwaway test code.
With automatically implemented properties in C# 3.0, it's easier than ever before to turn fields into properties. There's precious little reason not to do it.
Classes in other assemblies can derive from your unsealed classes and can access protected fields. If you one day decide to make those fields into properties, those classes in other assemblies will need to be recompiled to work with the new version of your assembly. That's called "breaking binary compatibility", and is perhaps the one solid reason why you shouldn't ever expose fields outside of an assembly.
I have to agree with Jon.
But, I use protected variable for "top most" inheritance class sometime in some condition. Example, if you have an object that is readonly and you cannot set it back BUT that you can use it in a child class, I do not see why I should have a protected Get to have access to that variable. A simple protected variable do the same encapsulation because you cannot set this variable and you can access this variable only from the child class.
But set/get is the way to do for other situation.
This is a trade-off here. Setters and getters are somewhat slower than accessing fields directly, so if you are doing heavy maths and read/write these fields a lot in your subclasses, you should go for accessing the fields directly. But this is more like an exception.
Normally, you should mark them as private and go for getters/setters.
So my answer is: direct access for heavily used fields, getters/setters otherwise. Use common sense.
EDIT: I did some profiling and apparently even in Release mode, there can be up the 20% speed difference between fields and properties. See my test case here: http://pastebin.com/m5a4d1597

Categories

Resources