Why do we use fields & properties instead of just a variable? [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#?
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.

Related

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.

Why do we use blank get; set; accessors in C#? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
c#: why have empty get set properties instead of using a public member variable?
string name;
vs
string name {get; set;}
Assuming your get and set are blank as above, what's the point in specifying them?
It encapsulates the compiler generated field, and provides you, the class or struct developer the ability to update it internally later without breaking your API by simply modifying the get/set part that you care about.
For instance, suddenly never want to return null? You can do that by simply changing the empty get to get { return storedName ?? ""; }. Of course, it means you suddenly need to manually control the variable, but that's a small price to pay for the flexibility.
The first use is an example of a field declaration. The second use is an example of an auto-implemented property.
It is generally bad practice to provide direct access to a field. However, the .NET team noticed that a lot of getters/setters are basically just that. For example, consider the following:
// C#
public string Name
{
get { return name; }
set { name = value; }
}
// Without properties (or a Java implementation)
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
Either way, that's a lot verbosity to really just expose a field. However, it is regularly the case that, as a developer, you need to go back and change how a field is handled internally, but you do not want to break or even affect other code if you can get away with it.
That is why using direct access to fields is bad. If you provide direct access to fields, but need to change something about using the field, then all code that uses that field must change as well. If you use a property (or even a method), then you can change the internal code and potentially not effect external code.
Consider the following example:
public string Name
{
get;
set;
}
Later you decide that you need to raise a changing and changed event around the setter. If you exposed a field, then it's time for a potentially big rewrite. If you used properties (or a method), then you can just add the logic there. You suddenly lose the benefit of auto-implementing properties, but you gained the ability to refactor your class without breaking existing code.
private string name;
public event NameChangingEventHandler NameChanging;
public event NameChangedEventHandler NameChanged;
public string Name
{
get { return name; }
set
{
OnNameChanging(/*...*/);
name = value;
OnNameChanged(/*...*/);
}
}
protected virtual void OnNameChanging(/*...*/) { }
protected virtual void OnNameChanged(/*...*/) { }
All of that maintains your public API and requires no work from users of the class (the rest of your code, or external developers using of your API). Breaking changes are not always avoidable, but avoiding direct access to fields is a good step to try to ensure that it won't happen. Auto-implemented properties are a quick, and easy way to do it.
(Unrelated: lost power while typing this and I am very happy that my browser saved most of it!)
The first one is actually a Field, but the second one is an Auto-Implemented property. The difference between them has already been discussed.
The first, assuming it's declared in class scope, is a field name. It's accessed as a field. The second is a property. A Blank get/set is known as an auto-property.
You might need to actually do something in your accessors in the future. Changing a field (which is what your first declaration is) to a property is a breaking change, so specifying accessors in advance is a small investment in the future.
Being able to add logic to a field's accessors without breaking compatibility is the standard explanation, and it's certainly a big one if you're writing a library or an application that's split among several assemblies that might be updated independently. I think it's something that one could dismiss as less of a concern if you're working on any sort of "all-in-one" software, though, since it'll all be recompiled anyway.
But even then, there's still another very compelling reason to only expose properties in your public interfaces: Even if you never need to make any internal updates, using fields can still lead to other problems on down the line because many portions of the .NET framework strongly prefer properties to fields. WPF, for example, does not generally support binding to fields. You can get around that by doing fancy things like implementing ICustomTypeDescriptor, but it's just so much easier to simply type {get; set;}.
string name {get; set;}
This is called auto implemented property. Actually, C# creates variable starting with _ itself, so on get, that variable value is fetched and on set, that variable value is set. Its just like normal properties. Where as string name; is just a field.
The first is a variable, the second is a (shorthanded) property
Properties are very nice, but as a general rule, objects shouldn't expose state to the public; they should be a black box from the perspective of outsiders. And you especially shouldn't state to direct change. State should change as a side effect of asking the object instance to do something useful in the problem domain.
If you are going to expose state, expose it as a read-only property (e.g. public widget Foo { get ; private set ; }).

What is the difference between public int i and public int i {get; set;} (what is the difference between automatic property and a public member?) [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
c#: why have empty get set properties instead of using a public member variable?
C#: Public Fields versus Automatic Properties
I am using "automatic" properties in my code,
and I wonder what is the actual difference between
this code:
public class foo{
public int i;
}
and
public class foo{
public int i {get; set;}
}
I know there is a difference, as sine 3rd parties that I've used missed the public members but found them once adding the {get; set;}.
AS there is no private field behind that, what is going behind the scene ?
A private field gets generated by the compiler when using automatic properties.
When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
In regards to the difference between the two examples - the first one exposes the field directly for manipulation. This is considered bad practice (think information hiding, loss of encapsulation).
With the second example, you must use the getter and setter and you can add any kind of validation and other logic around these actions.
See this blog post:
If I have a field with no special behavior, should I write a "just in case" property (with trivial get/set), or should I expose a public field?
The reason that the library design guidelines suggest you write a property here is that it is important that libraries be easily versioned. If you put a property in there ahead of time, you can change the property implementation without requiring users to recompile their code.
The first is a field and could be described as POD. The second is a property and allow for derived classes to overload and Shadow while the first does not. Also the second is a nicety since the complier silently creates a backing store.
That's an auto property, not an anonymous property. There is, in fact, a private backing field for it, it's just generated automatically by the compiler and isn't available to you at compile time. If you run your class through something like Reflector (or examine it at runtime with reflection), you'll see the backing field.
To answer your question of "What's the difference?", the obvious answer is that one is a field, whereas one is a property. The advantage to using auto properties is that it gives you the flexibility to move to traditional properties later, should the need arise, without changing your API. As far as third party code being able to "reach" one but not the other, that would be a question best answered by the other developer. That being said, most API's are designed to work on properties, not fields (since conventional wisdom is that you do not expose fields outside of the declaring class). If the third-party library is reflectively scanning your class, then it's likely only looking for properties.
The important thing to remember is that:
private string backingField;
public string Data
{
get { return backingField; }
set { backingField = value; }
}
and
public string Data { get; set; }
Are compiled to essentially the same code. The only substantive difference is the name of the backing field.

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.

When should we use private variables and when should we use properties. Do Backing Fields should be used in same class?

In most of the cases we usually creates a private variable and its corresponding public properties and uses them for performing our functionalities.
Everyone has different approach like some people uses properties every where and some uses private variables within a same class as they are private and opens it to be used by external environment by using properties.
Suppose I takes a scenario say insertion in a database.
I creates some parameters that need to be initialized.
I creates 10 private variables and their corresp public properties
which are given as
private string name;
public string Name
{
get{return name;}
set{name=value;}
}
and so on. In these cases mentioned above, what should be used internal variables or properties.
And in those cases like
public string Name
{
get{return name;}
set{name=value>5?5:0;} //or any action can be done. this is just an eg.
}
In such cases what should be done.
What is the conclusion
I actually meant to ask this.
Should we use variables within that class or not or should we use properties everywhere within same class as well.
If you use auto-implemented properties, then the field will be hidden, so you are forced to use the property, even in the class where the property is defined. Auto-implemented properties are a good idea, unless you need to add some logic to the getter/setter.
If the only use for the private variable is as a storage container, you might use:
public string Name {get; set;}
IMHO one should never make variables public - always use properties so you can add constraints or change behaviours later on whitout changing the interface.
Made things more readable:
I expose my data always through properties.
If I do not need additional logic (e.g. validation) I use implicit properties. This way there is no backing field and I cannot access it by accident. If I need to add some additional logic I can easily change the implicit property to a "traditional" one. As I use the property everywhere I do not have to worry that my extra logic is not called.
If I need something extra (like validation) then I have a private backing field, but I access this field only in the property body (get/set accessors). Again I do not need to worry if I change something in the property: My code will always use the same logic.
The only reason for not calling the property in my opinion would be if for some reason I really do not want any additional logic to be called, but this seems a dangerous thing so I rather avoid it...
I never expose public variables. Why? Because I can't lay constraints on them, whereas I can when I'm using properties. I can first check the value if it meets my constraints (e.g. an email address) and then I save it. Otherwise I throw an Exception.
You should never expose public variables without a very good reason. It is tough to say never, because if you trying to interop with comm type components you might be required too.
Anything publicly exposed should be a property. Why is that?
The reason is if you need to change the source of the value, or add some business logic checking if it is a public member you are going to require anything using the code to change. If it is a property you can change the internal logic and not require anybody using it to change the code.
I personally use properties and only create members variables when I want a property to do more than getting or setting (since this is easy with C# 3.0 with shortcut properties).
If I want to keep a property from being publicly exposed I make it as private, and only expose it when I have too.
We require explicit private variables in some situation like validation before set.Sometime we also need to conversion of input, for instance , formatting the input.

Categories

Resources