Properties in C# advantage [duplicate] - c#

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

Related

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

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.

Why do we use fields & properties instead of just a variable? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between a field and a property in C#?
Difference between Property and Field in C# .NET 3.5+
I have seen that in c# the following pattern is common:
private string m_name = string.Empty;
public string Name
{
get
{
return m_name;
}
set
{
m_name = value;
}
}
why do we use a field and a property to hold a value when we can use a simple variable?
why should I use fields and properties instead of a simple variable?
Just for encapsulation principle. For hinding concrete implementaiton, and plus, you have an opportunity (in this case) to add additional code inside get/set.
If you don't need addittional code, you can use just
public string Name{get;set;}
or use fileds, as you would like. But using properties is a guideline offered by Microsoft.
So basically all, follow it.
There are a lot of reasons for this, but 2 come to mind right away:
First, a property can be easily bound to a control or other reflection-based controls that read all properties (rather than fields).
Second, there may be actions that you want to perform in getters or setters (such as firing a NotifyPropertyChanged event).
Properties provide the opportunity to protect a field in a class by reading and writing to it through the property. In other languages, this is often accomplished by programs implementing specialized getter and setter methods. C# properties enable this type of protection while also letting you access the property just like it was a field.
Another benefit of properties over fields is that you can change their internal implementation over time. With a public field, the underlying data type must always be the same because calling code depends on the field being the same. However, with a property, you can change the implementation.

What is the difference between `Fields` and `Properties` in C#? [duplicate]

This question already has answers here:
What is the difference between a field and a property?
(33 answers)
Closed 8 years ago.
Edit, as per these comments:
Do you mean "Property" vs "Field"?
public String S1; vs public String S2
{ get; set; } – dana
Exactly dana, i mean the same. – Asad
Asad: you really need to try to use
some other term to describe what you
mean so that we can better understand
your question. C# does not have global
variables. The fields you can define
in C# are not global - they are
members of the class type. – dthorpe
Hi fellas,
Need your expert views over the difference between Field and Property. As in my project, I have used certain global variables which later on i changed to 'Properties' . My manager is asking what is the benefit of using Properties of variables instead of Fields.
Although I have replied him that Property provides a kind of secure/safe/indirect access to Field instead of modifying them directly if they are declared public or protected. But Please provide me with some more convincing arguments.
Thanks and Regards
#Asad:
You should get your terminology right: Fields are not Global Variables, C# does not have global variables (as a few commenters mentioned: you can simulate global variables, but you should not do that).
The main advantage is that you can attach all sorts of functionality to a property such as validation, synchronization etc. You can't do that for a class field. For example, a field can throw BCL exceptions on assignment but it can't throw an exception that make sense with logic in your problem domain.
Also imagine trying to protect a field for thread synchronization. You have to write extra code in all the places in your code where the field is accessed. To do that with a property you can simply wrap the getter and setter with a lock in one place. (But beware! The ease of using lock in property getters and setters can give you a false sense of security if you're working with mutable types. See the accepted answer in this post.)
Now, you might think that validation and synchronization are not important to you for this particular value, and they may never be for this particular instance. But by using properties instead of direct field access is making your application much more maintainable in the future. (Suppose the value of an integer field suddenly needs to come from a source different from the original implementation and it needs to be converted from a string to an int. If you use properties to wrap the field then you make the change in one place and all the client code that uses that property does not need to change at all!)
Also, for managing information shared across many classes (global) take a look at the singleton pattern. But beware! Even though it looks neat and clean you can still get into trouble with it. Though if you really need global data you should use properties contained in a singleton. If nothing else, it's a good organization strategy.
To avoid issues with singletons or "global" data take a look at dependency injection as a much better alternative.
C# syntax doesn't have a "global variable" declaration. It has properties and fields, and static properties and fields.
If by "global variable" you mean a static field or static property, that is different from a property or field in that the static field or property is not stored in the object instance data, it is stored in global memory. The value assigned to a static field or property is accessible to all instances of that class, and all instances see the same value. A static field is the closest thing C# has to the notion of "global variable" found in other programming languages.
A non-static property or field stores its data in the object instance data, so each instance of the object has its own local copy. Modifying object1.A property will not affect the value of object2.A property.
Have a look at Properties (C# Programming Guide)
A property is a member that provides a
flexible mechanism to read, write, or
compute the value of a private field.
Properties can be used as if they are
public data members, but they are
actually special methods called
accessors. This enables data to be
accessed easily and still helps
promote the safety and flexibility of
methods.
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
accessor is used to assign a new
value. These accessors can have
different access levels.
Properties that do not implement a
set accessor are read only.
I prefer properties because then when I use them in code I know exactly which class was used to call them (ex. class.property = value). Public class variables can become a real pain and waste of time when you are trying to figure out where they came from during debugging.

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