Difference in declaring public and private variables in a C# class - c#

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.

Related

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...? [C# properties GET/SET ways]

I know in C# you can easily create accessors to a data type, for example, by doing the following:
public class DCCProbeData
{
public float _linearActual { get; set; }
public float _rotaryActual { get; set; }
}
However my colleague, advised me to do it this way:
public class DCCProbeData
{
private float _linearActual = 0f;
public float LinearActual
{
get { return _linearActual; }
set { _linearActual = value; }
}
private float _rotaryActual = 0f;
public float RotaryActual
{
get { return _rotaryActual; }
set { _rotaryActual = value; }
}
}
My way seems simpler, and more concise. What are the differences and benefits of doing it either way?
Thanks
Edit Just a note, my colleague was able to generate the code for the "second way" using the Refactor option within the Class Details pane most easily found in a Diagram file. This makes it easy to add many Properties without having to manually create the accessors.
"Your way" just tells the compiler to create the second option. Unless you do something else in the getter or setter, they are functionally identical.
However, with "your way", I would recommend using the proper C# naming conventions. I would personally write this as:
public class DccProbeData
{
public float LinearActual { get; set; }
public float RotaryActual { get; set; }
}
The only difference is that you've named the fields.
(I'd stick with your colleagues naming convention for public properties though.)
They do the same thing internally. The only difference is that you cannot directly access the backing field variable using Auto Implemented Properties.
They are technically the same... the get/set is shorthand (auto property).
Lots of questions on SO about this:
When to use get; set; in c#
What is the { get; set; } syntax in C#?
Auto-Implemented Properties c#
Your way doesn't allow you to initialize the values, and your colleague's way follows a more-standard naming convention.
I would like to add something that I haven't seen in the other answers, which makes #2 a better choice:
Using the first method you cannot set a breakpoint on the get and set.
Using the second method you can set a breakpoint on the get and set, which is very helpful for debugging anything accessing your private variable.
Okay, the names have been mentioned before. It's also worth noting that as well as not being with the normal .NET conventions, beginning a public name with an underscore is not CLS-compliant (indeed, one reason for using it for private names is precisely because of this, it makes the distinction clearer, and should result in a warning with some code-checkers if you accidentally have the wrong access level).
Names aside, the one advantage to the latter form is that you can add more complicated code. Still, it's a non-breaking change to go from the former style to the latter, so there's no reason to do it before it's needed.
The first way is the way to go when you need simple properties with get and set and private storage done for you.
Use the second way if you need to do something special when you get or set the value.
Also, I recommend you stick to naming conventions using FxCop or ReSharper.
I believe at the IL level, they both end up the same. In the background, VS creates autonamed variables for you when using the auto getters and setters.
The only way this could possibly be better is if you feel you will be adding more logic to the getters and setters at a later date.
Even then, this seems a little pointless.
They are the same in the sense that your code sample will automatically generate backing fields.
But the two code samples are different because the names of the properties are not the same (LinearActual vs linearActual)
There is no difference, however prior to C# 3 you had to use the long way. At the end of the day it's a C# feature - syntactic sugar. They are both functionally identical.
Things you can do when you don't use auto-implemented properties:
initialize to a default value
access or annotate the backing field (attributes)
read-only backing fields or immutability
set a breakpoint on access
have custom code around access to the variable
Use [System.ComponentModel.EditorBrowsableAttribute()] to enable custom logic on the accessors that you avoid accidently bypassing while coding
hides the backing field from intellisense
Conversion between the two ways is made very simple with ReSharper.
This is not to say don't use them by all means use them, unless you have a need for any of the other functionality listed.

when and why to use C# accessor methods [duplicate]

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.

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.

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.

Categories

Resources