This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
C# - When to use properties instead of functions
I am trying to understand when and why to use "getters" and "setters"
would someone please provide some guidance.
What is the difference between the following constructs - please look in terms of accessor methods only.
//EXAMPLE 1: simple accessor method
private static bool _isInitialEditMapPageLoad;
public static bool isInitialEditMapPageLoad
{
get {return _isInitialEditMapPageLoad;}
set {_isInitialEditMapPageLoad = value;}
}
//EXAMPLE 2: accessor method with a conditional test
private static bool _isInitialEditMapPageLoad;
public static bool isInitialEditMapPageLoad
{
get
{
if (currentSession[isAuthorizedUseder] == null)
return false;
else
return _isInitialEditMapPageLoad;
}
set {isInitialEditMapPageLoad = value;}
}
//EXAMPLE 3: just a get accessor method - is this the same as EXAMPLE 4?
private static bool _isInitialEditMapPageLoad = false;
public static bool isInitialEditMapPageLoad
{
get {return _isInitialEditMapPageLoad;}
}
//EXAMPLE 4: simple method
private static bool _isInitialEditMapPageLoad = false;
public static bool isInitialEditMapPageLoad
{
return _isInitialEditMapPageLoad;
}
Your getters/setters should be your public interface to your class.
As a rule of thumb, all of your members should be private except for what you want people to have access to outside of your class and you never want your private variables to be directly accessible outside if your class
Here's a simple example. say you had a class that you needed an age variable for. In this case, you could perform validation right there in the setter without your external classes needing to know that the value is validated.
class Person {
int age = 0;
public int Age {
get { return age; }
set {
//do validation
if (valid) {
age = value;
}
//Error conditions if you want them.
}
}
//More getters/setters
}
The reasoning behind Getters/Setters is to protect the class from being broken when a user alters a field in an invalid way, and they allow you to change the implementation of your class while leaving the publicly exposed properties unchanged.
Unless you need some kind of validation or lazy-loaded properties then you can usually just use auto properties.
public string Name { get; set; }
1: This is a simple property, and can be used in much the same way as a public field. If you have a reason to expose both get and set operations to other users (that is, other classes) and you don't need anything fancy, this is it. This can also be written with "auto-properties",
public static bool isInitialEditMapPageLoad {get;set;} // behaves just like example 1
auto props are much faster to write and in my opinion are much more readable than the full declaration (if I see a full declaration with a backing field, I expect to find some complexity).
2: This shows one of the reasons for properties: using some logic to return a value rather than always returning a value directly. Somebody can set this value as they would a public field whenever they want. They can get the value whenever they want, as well, with the caveat that false means either this isn't the initial load OR the user isn't authorized -- that is, some (simple) logic is done before returning a value.
3: This behaves as a public field ONLY for reading -- somebody can retrieve the value, but not set it. This is in essence a value that is read only to outside code (not to be confused with the readonly keyword)
4: Resulted in a compilation error for me. Assuming that is supposed to be a method declaration, manually defining a getter like one would do in Java, then it is similar to example 3. I believe there are other issues that make this not quite the same, like if you want to turn this into a dependency property, etc. Unfortunately my knowledge in that area comes up short.
==========
As a general rule, user properties to limit access to your class data. As a principle, anything that you can keep from allowing other code to touch, should be kept that way. As a practical matter, you will want to be able to set values on classes to change how they display, modify the data represented, et cetera. Use properties to maintain maximum control of this interaction.
If other classes will need to view something in your class, you'll need to expose a getter, but not a setter. This isn't possible with fields, unless you use the Java method of writing a custom getter method. They also allow you to perform calculations or validations before returning or setting data. For example, if you have some integer value that should be within some range (a range which can change depending on the state of your object, even), in your setter you can check to make sure this condition is met before actually updating your value.
Try to avoid the trap of just setting everything as an autoprop -- this is no different than making everything a public field. Keep everything as private as possible. No getters unless necessary, no setters unless necessary, and setters should perform any small logic necessary to verify input before accepting it, if appropriate. That said, avoid the other trap: putting lots of code in getters/setters. If it takes more than a handful of lines, you should probably make a method rather than a property, simply because it gives a greater hint to others using your code that something big is going to happen.
Like others mentioned, use getters/setters when you want the object members to be available to other objects.
Additionally, the readability of yoru code could be improved (if you're on .NET 2.0 or greater) using autoproperties. The examples you have would then be like this:
// example 1
public static bool IsInitialEditMapPageLoad { get; set; }
// example 3/4 - note that false is the default for bools
public static bool IsInitialEditMapPageLoad { get; private set; }
Example 3 would likely stay the same, due to the validation logic being there.
Related
I have an example as follows:
public static String DocNum
{
get;
set;
}
private static String DocNum2;
public static String DocNum2GetSet {
get
{
return DocNum2;
}
set
{
DocNum2 = value;
}
}
I was wondering if one declaration benefits the other. Simple question, hoping for a simple answer.
There is no difference in usage; it's just that the first code is neater and therefore easier to write and read. The second code is required if you need to add any extra code, e.g. validation or raising an event in the setter.
In the second case, you are providing consistent API, where you can later modify the underlying structure without having to have consumers change their code.
For example, right now you are storing DocNum2 in a private string. You could later modify this to go get that data from a file or some other resource and the consumer of the code would be none the wiser.
The first example is referred to as an Auto-Implemented Property. It's shorthand for a full property which is the second of your examples. It's valid in C# 3.0 and later.
It's often sufficient but if you need custom logic or validation the full property is usually what you'll use. You'll also use the full property when doing things that implement INotifyPropertyChanged.
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 ; }).
I just realized that the C# property construct can also be used with a private access modifier:
private string Password { get; set; }
Although this is technically interesting, I can't imagine when I would use it since a private field involves even less ceremony:
private string _password;
and I can't imagine when I would ever need to be able to internally get but not set or set but not get a private field:
private string Password { get; }
or
private string Password { set; }
but perhaps there is a use case with nested / inherited classes or perhaps where a get/set might contain logic instead of just giving back the value of the property, although I would tend to keep properties strictly simple and let explicit methods do any logic, e.g. GetEncodedPassword().
Does anyone use private properties in C# for any reason or is it just one of those technically-possible-yet-rarely-used-in-actual-code constructs?
Addendum
Nice answers, reading through them I culled these uses for private properties:
when private fields need to be lazily loaded
when private fields need extra logic or are calculated values
since private fields can be difficult to debug
in order to "present a contract to yourself"
to internally convert/simplify an exposed property as part of serialization
wrapping global variables to be used inside your class
I use them if I need to cache a value and want to lazy load it.
private string _password;
private string Password
{
get
{
if (_password == null)
{
_password = CallExpensiveOperation();
}
return _password;
}
}
The primary usage of this in my code is lazy initialization, as others have mentioned.
Another reason for private properties over fields is that private properties are much, much easier to debug than private fields. I frequently want to know things like "this field is getting set unexpectedly; who is the first caller that sets this field?" and it is way easier if you can just put a breakpoint on the setter and hit go. You can put logging in there. You can put performance metrics in there. You can put in consistency checks that run in the debug build.
Basically, it comes down to : code is far more powerful than data. Any technique that lets me write the code I need is a good one. Fields don't let you write code in them, properties do.
perhaps there is a use case with nested / inherited classes or perhaps where a get/set might contain logic instead of just giving back the value of the property
I personally use this even when I don't need logic on the getter or setter of a property. Using a property, even a private one, does help future-proof your code so that you can add the logic to a getter later, if required.
If I feel that a property may eventually require extra logic, I will sometimes wrap it into a private property instead of using a field, just so I don't have to change my code later.
In a semi-related case (though different than your question), I very frequently use the private setters on public properties:
public string Password
{
get;
private set;
}
This gives you a public getter, but keeps the setter private.
One good usage for private get only properties are calculated values. Several times I've had properties which are private readonly and just do a calculation over other fields in my type. It's not worthy of a method and not interesting to other classes so private property it is.
Lazy initialization is one place where they can be neat, e.g.
private Lazy<MyType> mytype = new Lazy<MyType>(/* expensive factory function */);
private MyType MyType { get { return this.mytype.Value; } }
// In C#6, you replace the last line with: private MyType MyType => myType.Value;
Then you can write: this.MyType everywhere rather than this.mytype.Value and encapsulate the fact that it is lazily instantiated in a single place.
One thing that's a shame is that C# doesn't support scoping the backing field to the property (i.e. declaring it inside the property definition) to hide it completely and ensure that it can only ever be accessed via the property.
The only one usage that I can think of
private bool IsPasswordSet
{
get
{
return !String.IsNullOrEmpty(_password);
}
}
Properties and fields are not one to one. A property is about the interface of a class (whether talking about its public or internal interface), while a field is about the class's implementation. Properties should not be seen as a way to just expose fields, they should be seen as a way to expose the intent and purpose of the class.
Just like you use properties to present a contract to your consumers on what constitutes your class, you can also present a contract to yourself for very similar reasons. So yes, I do use private properties when it makes sense. Sometimes a private property can hide away implementation details like lazy loading, the fact that a property is really a conglomeration of several fields and aspects, or that a property needs to be virtually instantiated with each call (think DateTime.Now). There are definitely times when it makes sense to enforce this even on yourself in the backend of the class.
I use them in serialization, with things like DataContractSerializer or protobuf-net which support this usage (XmlSerializer doesn't). It is useful if you need to simplify an object as part of serialization:
public SomeComplexType SomeProp { get;set;}
[DataMember(Order=1)]
private int SomePropProxy {
get { return SomeProp.ToInt32(); }
set { SomeProp = SomeComplexType.FromInt32(value); }
}
I use private properties to reduce code for accessing sub properties which often to use.
private double MonitorResolution
{
get { return this.Computer.Accesories.Monitor.Settings.Resolution; }
}
It is useful if there are many sub properties.
One thing I do all the time is store "global" variables/cache into HttpContext.Current
private static string SomeValue{
get{
if(HttpContext.Current.Items["MyClass:SomeValue"]==null){
HttpContext.Current.Items["MyClass:SomeValue"]="";
}
return HttpContext.Current.Items["MyClass:SomeValue"];
}
set{
HttpContext.Current.Items["MyClass:SomeValue"]=value;
}
}
I use them every now and then. They can make it easier to debug things when you can easily put in a breakpoint in the property or you can add a logging statement etc.
Can be also be useful if you later need to change the type of your data in some way or if you need to use reflection.
I know this question is very old but the information below was not in any of the current answers.
I can't imagine when I would ever need to be able to internally get but not set
If you are injecting your dependencies you may well want to have a Getter on a Property and not a setter as this would denote a readonly Property. In other words the Property can only be set in the constructor and cannot be changed by any other code within the class.
Also Visual Studio Professional will give information about a Property and not a field making it easier to see what your field is being used.
It is a common practice to only modify members with get/set methods, even private ones. Now, the logic behind this is so you know your get/set always behave in a particular way (for instance, firing off events) which doesn't seem to make sense since those won't be included in the property scheme... but old habits die hard.
It makes perfect sense when there is logic associated with the property set or get (think lazy initialization) and the property is used in a few places in the class.
If it's just a straight backing field? Nothing comes to mind as a good reason.
Well, as no one mentioned you can use it to validate data or to lock variables.
Validation
string _password;
string Password
{
get { return _password; }
set
{
// Validation logic.
if (value.Length < 8)
{
throw new Exception("Password too short!");
}
_password = value;
}
}
Locking
object _lock = new object();
object _lockedReference;
object LockedReference
{
get
{
lock (_lock)
{
return _lockedReference;
}
}
set
{
lock (_lock)
{
_lockedReference = value;
}
}
}
Note: When locking a reference you do not lock access to members of the referenced object.
Lazy reference: When lazy loading you may end up needing to do it async for which nowadays there is AsyncLazy. If you are on older versions than of the Visual Studio SDK 2015 or not using it you can also use AsyncEx's AsyncLazy.
One more usage would be to do some extra operations when setting value.
It happens in WPF in my case, when I display some info based on private object (which doesn't implement INotifyPropertyChanged):
private MyAggregateClass _mac;
private MyAggregateClass Mac
{
get => _mac;
set
{
if(value == _mac) return;
_mac = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(DisplayInfo)));
}
}
public string DisplayInfo => _mac.SomeStringInformationToDisplayOnUI;
One could also have some private method, such as
private void SetMac(MyAggregateClass newValue)
to do that.
Some more exotic uses of explicit fields include:
you need to use ref or out with the value - perhaps because it is an Interlocked counter
it is intended to represent fundamental layout for example on a struct with explicit layout (perhaps to map to a C++ dump, or unsafe code)
historically the type has been used with BinaryFormatter with automatic field handling (changing to auto-props changes the names and thus breaks the serializer)
Various answers have mentioned using properties to implement a lazy member. And this answer discussed using properties to make live aliases. I just wanted to point out that those two concepts sometimes go together.
When using a property to make an alias of another object's public property, the laziness of that property is preserved:
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private IDbConnection Conn => foo.bar.LazyDbConnection;
On the other hand, retrieving that property in the constructor would negate the lazy aspect:
Conn = foo.bar.LazyDbConnection;
Looking into the guideline (Properties (C# Programming Guide)) it seems no one expects to use properties as private members.
Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.
In any case it can be interchanged by one or two methods and vice versa.
So the reason can be to spare parentheses on getting and get field syntax on setting.
Is there a difference between:
public T RequestedValue { get; set; }
and
public T RequestedValue;
?
Taken from this code:
public class PropertyChangeRequestEventArgs<T>:EventArgs
{
public PropertyChangeRequestEventArgs(T pRequestedValue)
{
RequestedValue = pRequestedValue;
}
public T RequestedValue { get; set; }
}
The first is an Auto-Implemented Property the second is a Field. Regular Properties expose Getters and Setters but have a private field to actually store the value:
private int someProperty;
public int SomeProperty
{
get { return someProperty; }
set { someProperty = value; }
}
The first allows you to change certain aspects of the implementation of your class without affecting all the other code in your application. The most important point is that, with properties, changes can be made without breaking binary compatibility (although a field can often be changed to a property without breaking code). If it is a public member, a property is advisable. (Stealing shamelessly from Snarfblam's comment)
From the Properties page:
Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. 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 with a backing field are the most flexible form as they allow easy implementation of things like the INotifyPropertyChanged event for updating the UI in Model-View-ViewModel implementations.
deep explanation!
The {get; set;} is an automatic property, while the second is a field.
a field is a normal variable, from some type, that contains data.
a property is a couple of methods (well sometimes it's just one), one for get, and one for set. they only have a syntax like fields, but actually they are quite different.
properties are usually for filtering the set of the value, or virtualizing something in the get, etc.
automatic properties, also create a private field behind the scenes, return its value in the get, and set its value in the set.
seemingly this is just like a normal field, but behind the scenes (IL) using properties is totally different from using fields.
a.Property1 = 4;
is translate into something like:
a.Set_Propert1(4);
and this:
x = a.Property1;
is translate to something like this:
x = a.Get_Property1();
so why is it a good practice to use only public properties, even if they are automatic?
say you are writing a library, that is used by other application, and someday you want to release a new version of that library that constrains one of your class' fields..
if you are using properties, you can just change the property (even if it is an automatic one, you can replace it by a full one), and then any application which used your library can still use it in the same way.
but if you made a public field, which you now want to constrain, you'll need to make a property for this and make the field private, but if you will, any application that used you library will no more be bale to, because the way it use fields and property is different.
You may write:
public T RequestedValue { get; set; }
as a shortcut of:
private T _requestedValue;
public T RequestedValue
{
get { return this._requestedValue; }
set { this._requestedValue = value; }
}
They are totally equivalent, also considering the performance.
The answer is, yes you can remove the { get; set; } but then a whole load subtle differences kick in. Some will say fields and properties express radically different design intent but in practice this distinction has been eroded over the years as C# evolves and progressively blurs the the syntactic differences.
For a good list of compiler-binary level differences between fields and properties refer to SO question difference-between-property-and-field-in-c. But the answers to that question missed one significant point about the special role of properties when declaring interfaces.
This question already has answers here:
Should you access a variable within the same class via a Property?
(6 answers)
Closed 9 years ago.
This is something that I've always wrestled with in my code. Suppose we have the following code:
public class MyClass {
private string _myVariable;
public string MyVariable {
get { return _myVariable; }
set { _myVariable = value; }
}
public void MyMethod() {
string usingPrivateMember = _myVariable; // method A
string usingPublicProperty = MyVariable; // method B
}
}
Which way is more correct - method A or B? I am always torn about this. Method A seems like it would be minutely faster, due to the fact that it doesn't have to go access a property before getting the real variable. However, method B is safer because if the getter for MyVariable gets business logic added to it, you are safe by always calling it, even if there is no current business logic.
What's the general consensus?
Use the property.
I think the property should be wholly responsible for managing that field.
There are plenty of implementations where it won't matter, but there are lots where it does matter -- a lot. Plus, this can be a bit of a pain to track down, because it always looks right.
You'll go wrong calling the property far fewer times than calling the field, and where there are exceptions to this rule, document the rationale.
This would really depend on what you are accessing the property for. Consider the following two scenarios:
Scenario 1: you write a method to provide a common action on the data in the class:
// assume a hypothetical class Position
public class Circle
{
private int _radius;
private int _xpos;
private int _ypos;
public int Radius { get { return _radius; } }
public Position Center { get { return new Position(_xpos, _ypos); } }
public bool PointInCircle(Position other)
{
return distance(this.Center, other) < this.Radius;
}
}
Clearly the behavior of PointInCircle should be the same as if the user executed the code inside it. Therefore, it makes sense to use the public properties.
Scenario 2: you write a method to manipulate the underlying data. A good example of this is serialization. You would want to serialize the underlying data members as opposed to the values returned by property accessors.
depends, if you access the property, there might be 'validation' code that is called.
private int timeSinceLastPropertyAccess;
public int TimeSinceLastPropertyAccess
{
get
{
// Reset timeSinceLastPropertyAccess to 0
int a = timeSinceLastPropertyAccess;
timeSinceLastPropertyAccess = 0;
return a;
}
}
Do you want timeSinceLastPropertyAccess to be reset when it is used when inside your class or not?
Just to add one more thing, your example only asked about getters. The other half of this is setters.
Sometimes you will want the object to use the setters and sometimes you would want it to bypass them and just assign the underlying field.
For example, let's say you have a property called IsModified. Which would tell you whenever the object has been modified. You could have all of your setters flip this to true in the event a different value is assigned to one of the underlying fields.
Now if you are hydrating that object (either loading from a db or somewhere else) then you wouldn't want IsModified set. Because, quite frankly, it isn't modified yet. So in that method you use the underlying field names, but in all of the other methods you use the property setter.
it depends, do you want to do what the property does? private/public doesn't really matter, its just like calling a function.
as it is, you have really just set up a "function" in anticipation of having to do something whenever that value is accessed or changed.
the problem with doing this is you might come to find you want to do one thing where its accessed in some places, and another when its accessed in other places, so you are still going to have to change all the 'calls' to it in one of the places.
fact of the matter is, if EVERYTHING that access that variable - even the private class functions - does so through the property that just passes through the variable, why bother having the property at all? why not just create the variable called 'MyVariable' then if you find you wanna do something when its changed/accessed, just create another variable called _MyVariable or something, then change MyVariable to be a property for _MyVariable then.
you should think of properties as being just like the accessor() and mutator() functions you used to write, the trick with them was, if you found that you DID want to do some code whenever a variable was 'accessed' you had to change ALL the calls to that variable to use an accessor instead (calling a function, rather than just accessing a member variable), that is why you would create 'default' accessors and matadors, just in case. As I have stated above, you don't have that problem with c# and properties (except in one lame case where you can't write to the sub members of a member if its a property... WHY??)