Within the Containing Class, Use Property or Field? - c#

Is it good practice to use the private field, or the property, when writing code in the class that contains them?
For example, if I have this field/property pair, classes outside this class must use the property. What about code inside the class? Should it use the private field, or should it also go through the property?
private string _foo;
protected string Foo
{
get { return this._foo; }
}
private void SomeMethod()
{
string dummyVariable = "snuh" + this._foo; // So, this...
string dummyVariable = "snuh" + this.Foo; // ... or this?
}
One advantage of using the property here, is if there is any logic in the getter, it will still get executed. I'm curious to know if there is a best-practice policy to follow here.

When using Auto-Implemented properties, you don't have a choice - you must use the property, as you don't have any access to the generated field.
If you property is not simple and does some extra work (validation, firing events etc...), you should call the property in order to centralize access and logic.
If you have any other properties (meaning a simple property with no logic and a backing field) I would ask why are they not one of the above...
With the example you have give, it makes little difference - it is more important to be consistent with how you use these and really boils down to personal aesthetics and coding style.

Related

Are there any reasons to use private properties in C#?

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.

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.

Overloading properties in C#

Ok, I know that property overloading is not supported in C# - most of the references explain it by citing the single-method-different-returntype problem. However, what about setters? I'd like to directly assign a value as either a string or object, but only return as a string.
Like this:
public string FieldIdList
{
get { return fieldIdList.ToString(); }
set { fieldIdList = new FieldIdList(value); }
}
public FieldIdList FieldIdList
{
set { fieldIdList = value; }
}
private FieldIdList fieldIdList;
Why wouldn't this be allowed? I've also seen that "properties" simply create getter/setter functions on compile. Would it be possible to create my own? Something like:
public void set_FieldIdList(FieldIdList value)
{
fieldIdList = value;
}
That would do the same thing. Thoughts?
Properties are in fact a pair of get/set methods (one of which may be left out), but the property itself has additional metadata which makes it a property in the first place instead of just two methods.
Because the property signature remains invalid as per only-different-by-return-type, even if you only have a setter. If you need this, don't use a property; set-only properties aren't a good thing anyways.
One approach (you may argue amongst yourselves as to whether this is a good design choice or not) is to add a second property, which accesses the data in a different form.
However, as it is going to be parsing the string (doing significant work), it would be better not to use a property for this, but to add methods that allow you to get/set the data in a string form.
I'd go for fieldIdList providing ToString() and TryParse() interfaces - then if you need it as a string, you'd call myObject.FieldIdList.ToString() etc. This encapsulates everything tidily, allows you to convert to/from string formats anywhere in your code rather than only when accessing FieldIdLists as a member of some other class, and makes the client code really clear and easy to understand.
If you want to be able to set a property as either a string or an object then you would just use object as the type of the property, since it's the base class (you can pass a string to a property that accepts an object). This doesn't seem particularly good design decision, but it can be done. Perhaps you need to explain further what you are trying to achieve?
You cannot overload C# properties as of C#7.
However, a redesign including your property is possible.
You can use a condition in your set block to call a private function,
which can be overloaded.
public string FieldIdList
{
get { return fieldIdList.ToString(); }
set { fieldIdList = ChangeFieldList(value); }
}
private string ChangeFieldIdList(int i) {
return i.ToString();
}
This example is just mean't to show a redesign consideration using private functions
to be called within the set block.

Do you use Data Members or Public Properties from within the Class itself?

If I have a simple class setup like this:
class MyClass
{
private string _myName = string.Empty;
public string MyName
{
get
{
return _myName;
}
}
public void DoSomething()
{
// Get the name...
string name = string.Empty;
name = _myName;
// OR
name = MyName;
// ...and do something with it...
}
}
Which should I use, the public property, or the data member?
Obviously, in this example it doesn't make a difference, since they both just reference the same variable. But what about real world uses of Public Properties?
In general, do Public Properties perform very little, in which case it is OK to call them? Or do people put a lot of functionality into their Public Properties that should not be called by internal class references?
I saw something in another post about NOT putting lots of functionality into Properties, since examining them in the Debugger can perform unexpected results. Is that true?
Use the property - any logic that may be encapsulated within the setters and getters ought to apply, even within the class itself. If there is no logic within the getters and setters it is still not safe to use the fields themselves because if at any point you wish to add logic around the access to those fields you will have to refactor much more.
I believe that you should reference the property as a general practice. While in this particular example it really doesn't make much of a difference, the get/set accessors offer the ability to do a bit more work when grabbing a property. For example, many of our property "get" accessors perform some lookup within a more complex data structure or set default values if nothing has been defined. So that the rest of the class can take advantage of this logic, we make a habit of using the properties. Just so we don't have to think too hard about it, we try to generalize the practice.
There may be instances in which we want to directly access the underlying data member, but then that is a conscious decision with a specific reason and it tends to be the exception.
I prefer properties because they easily handle read-only situations and it's easy to wrap them with any basic validation you might need to do.
If I'm just returning the value of the internal variable, I make the variable public - there's no harm to doing so. I've always used Public Properties when I want to do something in response to either a viewing or a changing of the value - ie, write it to a database, set something else too (as in the second part of your example).
The question you have to ask is whether you want what happens inside your class to trigger these events. If you do, the same way an external caller would, then access the values via the property. If you just want to read the value, use the internal variable.
To answer your question, there's no harm to doing it either way - just consideration of the potential side-effects.

When inside a class, is it better to call its private members or its public properties? [duplicate]

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??)

Categories

Resources