I've been working on creating a class and suddenly a thought came to my mind of what is the difference between the two codes:
public readonly string ProductLocation;
AND
public string ProductLocation
{
get;
private set;
}
Can you guys give me idea when to use the following better. thanks.
The first one is a read-only field, while the second one gets compiled as a pair of methods (and all reads of the property ProductLocation gets compiled into calls to the corresponding get method and writes to it gets compiled into calls to the set method; internally, these methods will read from / write to an internal, automatically generated, non-read-only field). I'd say the most important difference is thread-safety! (how? read on!)
The basic usage of the class will look exactly the same: code in other classes will only be able to read the value, not change it. Also, the code to read the value will look exactly the same (for example, print(myInstace.ProductLocation); here, you cannot tell how it has been declared, cool, eh?)
The first, most trivial difference is that the property with private setter allows for instances of the same class to modify the value, while in the case of the readonly property, not even the object itself will be able to change the value.
Now, for the thread-safety. The readonly attribute on the field will change its memory visibility semantics when you are working with multiple threads (just like Java's final fields).
A readonly field can only be assigned to at declaration or in the constructor. The value assigned to a readonly field cannot be changed (at least not in a normal way) and it is guaranteed that every thread will see the correctly, initialized value after the constructor returns. Therefore, a readonly field is inherently thread-safe.
To achieve the same thread-safety with the property, you'd have to add some synchronization on your code, which is error-prone. It might lead to dead-locks, data races or reduced performance, depending on the case, and especially if you are not experienced.
So, if the value represents something that semantically cannot be changed after the object's construction, you should not declare a private setter (this would imply that the object might change it). Go for the readonly field (and maybe declare it private and declare a public property with only a getter accessing the field! This is actually the preferred form, since it is not good to expose fields, it is better to only expose methods -- there are many reasons explaining why in this answer)
With C# 6.0 auto-property initializer there is less boilerplate way of doing
private readonly string productLocation;
public string ProductLocation { get { return productLocation; } }
Which is
public string ProductLocation { get; }
This is readonly. Only initialized from constructor or inline. It cannot be edited after initialization. (Immutable from anywhere)
However, if you use private set;
public string ProductLocation { get; private set }
This is readonly from outside. But can be initialized anytime anywhere within the class itself. And can be edited within its life cycle by the class itself. (Mutable from class, immutable from outside)
Generally, it is not encouraged in .NET to expose member fields publicly, those should be wrapped by a property. So let's assume you might have
private readonly string productLocation;
public string ProductLocation { get { return productLocation; } }
vs
public string ProductLocation { get; private set; }
In this setup, and ignoring what one might be able to accomplish via reflection, the semantics are that in the first case, the productLocation variable can only be initialized in place and in the class constructor. Other members of the class cannot alter the value. External consumers have no ability to set the value.
In the second version, external consumers continue to have no access towards setting the value. However, the class itself can change the value at any time. If all you have is a DTO (that is, a class that only transports data, it has no logic expressed via methods), then this is essentially not all that different from the readonly version. However, for classes with methods, those methods could alter the value behind ProductLocation.
If you want to enforce the concept of an immutable field post-construction, use readonly. But for a DTO, I might go for the private set; option, mainly because it is less boilerplate code.
The first one (using readonly) will mean that the object can't even modify its own field's value, once the object has been instantiated, and others can never modify it.
The second one (using private set) will mean that object can modify the value of its field after it's been instantiated, but others can never modify it.
I would use the former for something that you know will not change, and use the latter for something where the value may change, but you don't want others to change it.
The first is a field whose value can be set only at instantiation.
The second is a property whose value can be set at any time (but only by its containing object).
Correction: The property can be set at any time by any instance of the same class (and not only by its containing object).
Related
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.
My class contains LOT_SIZE constant which can not be changed. But I can initialize it only during execution, because I obtain LOT_SIZE from Securities table at runtime. However I want to make clear that this is constant and I want to protect it from changes from any other places except one "friend" place where I want to initialize it ("Securities" table read).
Do we have something for that in C# or I just have to use LOT_SIZE as regular variable?
I can not declare LOT_SIZE as readonly because during object construction "Securities" table still not read and so I don't know LOT_SIZE value.
The best way is probably to read the value before creating the class that must hold it, so you can pass it into the constructor and put it into a readonly field. But as you've excluded doing it the obvious way...
You could use a read-only property (a property with a get but no set) and always access it via the property except in the place where you initially set up the value.
If you don't even want to risk changing it from within your own class, then create a class to "wrap" the value. This class would do nothing more than read the value when required the first time and expose it as a read-only property to your consumer classes.
But whichever way you choose, please don't use "1970's C macro constant" (ALL_CAPS) naming for your constant :-)
You cannot declare a variable in a way that it can be modified in one place and not in any other (except for readonly which you excluded).
I suggest you use some kind of "lazy pattern". Write a class which wraps a value and allows the value to be set exactly one time. You can make the variable referencing an instance of this class read-only.
class WriteOnce<T>
{
T _val;
bool _isInitialized;
public T Value {
get { if (!_isInitialized) throw; return _val; }
set { if (_isInitialized) throw; _val = value; }
}
}
...
class SomeOtherClass {
readonly WriteOnce<int> LOT_SIZE = new WriteOnce<int>();
}
You could make a class to read from your table with a private member variable (even make the class a Singleton to get uber fancy). Then make a static public variable with only a getter. It's a bit overkill, but that would be the only way to allow it to be set after initialization, but only able to be modified the one time.
I'm fairly new to C#, and I think properties are a wonderful thing. So wonderful, in fact, that I can't see any real advantage to using fields, instead. Even for private fields, it seems like the flexibility and modularity that properties offer can at best save you serious headaches, and at worst have no effect at all.
The only advantage I can see for fields is that you can initialize them inline. But most of the time, you want to initialize them in the constructor, anyway. If you aren't using inline initialization, is there any reason not to use properties all the time?
Edit: Some people have brought up the need to back up properties with fields (either explicitly or automatically). Let clarify my question: Is there any reason to use fields except to back up properties? I.e., is there any time that SomeType someField; is preferable to SomeType SomeProperty { get; set; }?
Edit 2: DanM, Skurmedel, and Seth all gave really useful answers. I've accepted DanM's, as it is the most complete, but if someone were to summarize their responses into a single answer, I'd be happy to accept it.
Typically, properties need a backing field unless they are simple getter/setter "automatic properties".
So, if you're just doing...
public string Name { get; set; } // automatic property
...you don't need a field, and I agree, no reason to have one.
However, if you're doing...
public string Name
{
get { return _name; }
set
{
if (value = _name) return;
_name = value;
OnPropertyChange("Name");
}
}
...you need that _name backing field.
For private variables that don't require any special get/set logic, it's really a judgment call whether to do a private automatic property or just a field. I usually do a field, then, if I need it to be protected or public, I will change it to an automatic property.
Update
As noted by Yassir, if you use automatic properties, there's still a field lurking behind the scenes, it's just not something you actually have to type out. So, the bottom line is: properties don't store data, they provide access to data. Fields are what actually hold the data. So, you need them even if you can't see them.
Update 2
Regarding your revised question...
is there any time that SomeType someField; is preferable to SomeType SomeProperty { get; set; }?
...one thing that comes to mind: If you have a private field, and (according to convention for private fields) you call it _name, that signals to you and anyone reading your code that you are working directly with private data. If, on the other hand, you make everything a property, and (according to convention for properties) call your private property Name, now you can't just look at the variable and tell that it is private data. So, using only properties strips away some information. I haven't tried working with all properties to gauge whether that is crucial information, but something is definitely lost.
Another thing, more minor, is that public string Name { get; set; } requires more typing (and is a little messier) than private string _name.
Just try using a Property when using ref/out args:
someObject.SomeMethod(ref otherObject.SomeProperty);
It won't compile.
Properties are a wonderful thing -- but there is overhead associated with property access. Not necessarily a problem, but something to be aware of.
Avoiding Overuse of Property Getters and Setters
Most people don't realize that property getters and setters are similar to methods when it comes to overhead; it's mainly syntax that differentiates them. A non-virtual property getter or setter that contains no instructions other than the field access will be inlined by the compiler, but in many other cases, this isn't possible. You should carefully consider your use of properties; from inside a class, access fields directly (if possible), and never blindly call properties repeatedly without storing the value in a variable. All that said, this doesn't mean that you should use public fields!
Source: http://dotnet.sys-con.com/node/46342
If you want to have something readonly you pretty much have to use a field as there is no way to tell an automatic property to generate a read-only field.
I do this quite often.
Contrived example:
class Rectangle
{
private readonly int _width;
private readonly int _height;
public Rectangle(int width, int height)
{
_width = width;
_height = height;
}
public int Width { get { return _width; } }
public int Height { get { return _height; } }
}
This means nothing inside of Rectangle can alter the width or height after construction. If one tries to the compiler will complain.
If I instead had used an automatic property with a private setter the compiler wouldn't protect me from myself.
Another reason I see is, if a piece of data doesn't have to be exposed (stay private) why make it a property?
While I agree with what I perceive as the "intent" in David Basarab's statement : "There is no reason to publicly expose fields," I'd like to add a slightly different emphasis :
I'd modify the quote from David above to read : "There is no reason to publicly expose fields ... outside a class ... except through the conscious choice of encapsulating the fields in Properties through which access is rigorously controlled.
Properties are not simply a "veneer" of syntax over Fields "tacked onto" C# : they are a fundamental language feature designed for good reasons including :
controlling what is exposed and not exposed outside classes (encapsulation, data hiding)
allowing certain actions to be performed when a Property is accessed or set : actions that are best expressed in the Property 'get and 'set, rather than being "elevated" to externally defined methods.
Interfaces by design cannot define 'fields : but can define Properties.
Good OO Design means making conscious choices about "state" :
local variable fields : what state is private to a method and transient : local variables typically only valid within the scope of a method body, or even with as "narrow a lifespan" as within the scope of something like a 'for loop. Of course you can regard parameter variables in a method as "local" also.
class instance fields : what state is private to a class, and has independent existence for each instance of a class, but is most likely required to be used in several places in the class.
static instance fields : what state will be a property of the class only, independent of the number of instances of the class.
state deliberately and consciously exposed "outside" the class : the key idea being that there is at least one level of indirection interposed between the class and "consumers" of the data the class exposes. The "flip side" of "exposure" is, of course, the conscious intention of hiding (encapsulating, isolating) implementation code.
a. via public properties : all aspects of this well-covered in all the other answers here
b. via indexers
c. via methods
d. public static variables are usually found in utility classes, which are often static classes.
Suggest you review : MSDN on 'Fields ... MSDN on Properties ... MSDN on Indexers
I don't see why you'd use private autoproperties. What advantage is there to
private int Count {get; set;}
over
private int count
Fields and properties are not interchangeable. I guess what you're saying is accessing private fields through private properties. I do this when it makes sense but for the most part, it's not necessary. The JIT optimizer will inline access to a private field through a private property in most cases anyway. And wrapping a private field in a private property is not considered a breaking change anyway since private members are not a part of your interface.
Personally, I would never expose any protected/public instance fields. It's generally acceptable though to expose a public static field with a readonly modifier as long as the field type is itself immutable. This is often seen with SomeStruct.Empty static fields.
As others have noted, you will need a private backing field for properties anyway.
Also there is a speed advantage in using fields over properties. In 99.99 % of the cases it won't matter. But in some it might.
Fields are the only place you can store state. Properties are actually just a pair of methods with special syntax that allows them to be mapped to the get or set method depending on how they're being used: if a property modifies or accesses state, that state still has to be stored in a field.
You don't always see the fields. With C# 3 automatic properties, the field is created for you by the compiler. But it's still there. Furthermore, automatic properties have some significant limitations (e.g. no INotifyPropertyChanged support, no business logic in setters) that mean they're often inappropriate, and you need to create an explicit field and a manually defined property anyway.
As per David's answer, you're right if you're talking about an API: you almost never want to make the internal state (fields) part of the API.
The syntax for fields is a lot quicker to write than for properties, so when it's safe to use a field (private to the class) why not use it and save that extra typing? If auto-implemented properties had the nice short concise syntax and you had to do extra work to make a plain old field, people might just start use properties instead. Also, it's a convention now in C#. That's how people think, and it's what they expect to see in code. If you do something different form the normal, you will confuse everyone.
But you could ask why the syntax for fields doesn't create an auto-implemented property instead of a field, so you get the best of both worlds - properties everywhere and a concise syntax.
There's a very simple reason why we still need to have explicit fields:
C# 1.0 didn't have all these nice features that we have now, so fields were a fact of life - you couldn't really live without them. Lots and lots of code relies on fields and properties being visibly different things. It simply cannot be changed now without breaking tons of code.
I would suspect also that there are performance implications, but perhaps that can be solved by the jitter.
So we're stuck with fields forever, and since they're there and they've taken the best syntax, it makes sense to use them when it's safe to do so.
There is no reason to publicly expose fields.
If you public expose a field you can't change the source of the information, from inline defination to configuration file without refactoring.\
You could use a field to hide internal data. I rarely favor that, I only use fields when I am doing something to hide publicly and using it in a property. (i.e. I am not using Automatic property generation)
Speed. If a field gets set or read billions of times over the course of a simulation then you want to use a field and not a property to avoid the overhead och a sub routine call. Conforming to OO (DDD?) as far as possible, in these instances, I'd recommend resorting to fields only in class dedicated to representing some sort of "value" like person. Logic should be kept to a minimum. Rather, have a personcreator or a personservicer.
But if you have these issues then you're probably not programming c++ and not c#, aren't you?
There are several good (partial) answers by #Seth (fields perform better, so in a private context you might as well use that to your benefit when it makes sense), #Skurmedel (fields can be readonly), #Jenk (fields can be used for ref/out). But I'd like to add one more:
You can use the streamlined initialization syntax for setting the value of a field, but not a property. i.e.:
private int x = 7;
vs
private int x { get; set; }
// This must go in the constructor, sometimes forcing you to create
// a constructor that has no other purpose.
x = 7;
Seen a few examples of code where this happens:
public class Foo
{
string[] m_workID;
public string[] WorkID
{
get
{
return m_workID;
}
private set
{
m_workID = value;
}
}
}
What's the point of this?
Since the use m_workID unnescessary.
In general, the point is to separate implementation (the field) from API (the property).
Later on you can, should you wish, put logic, logging etc in the property without breaking either source or binary compatibility - but more importantly you're saying what your type is willing to do, rather than how it's going to do it.
I have an article giving more benefits of using properties instead of public fields.
In C# 3 you can make all of this a lot simpler with automatically implemented properties:
public class Foo
{
public string[] WorkID { get; private set; }
}
At that point you still have a public getter and a private setter, but the backing field (and property implementation) is generated for you behind the scenes. At any point you can change this to a "normal" fully-implemented property with a backing field, and you'll still have binary and source compatibility. (Compatibility of serialized objects is a different matter, mind you.)
Additionally, in this case you can't mirror the behaviour you want (the ability to read the value publicly but write it privately) with a field - you could have a readonly field, but then you could only write to it within the constructor. Personally I wish there were a similar shorthand for this:
public class Foo
{
private readonly int id;
public int Id { get { return id; } }
...
}
as I like immutable types, but that's a different matter.
In another different matter, it's generally not a good idea to expose arrays like this anyway - even though callers can't change which array WorkID refers to, they can change the contents of the array, which is probably not what you want.
In the example you've given you could get away without the property setter, just setting the field directly within the same class, but it would mean that if you ever wanted to add logging etc you'd have to find all those writes.
A property by itself doesn't provide anywhere to put the data - you need the field (m_workID) for storage, but it entirely correct to hide that behind a property for many, many reasons. In C# 3.0 you can reduce this to:
public string[] WorkID {get; private set;}
Which will do much of the same. Note that exposing an array itself may be problematic, as there is no mechanism for protecting data in an array - at least with an IList<string> you could (if needed) add extra code to sanity check things, or could make it immutable. I'm not saying this needs fixing, but it is something to watch.
In addition to the Object Oriented philosophy of data encapsulation, it helps when you need to do something every time your property is read/write.
You can have to perform a log, a validation, or any another method call later in your development.
If your property is public, you'll have to look around all your code to find and modify your code. And what if your code is used as a library by someone else ?
If your property is private with appropriate get/set methods, then you change the get/set and that's all.
You can use C# 3.0 auto properties feature to save time typing:
public class Foo
{
public string[] WorkID
{
get; private set;
}
}
In addition properties gives you lot of advantages in comparison to fields:
properties can be virtual
properties hide implementation details (not all properties are just trivial variable accessors)
properties can contain validation and logging code and raise change events
interfaces cannot contains fields but properties
A lot of times you only want to provide read access to a field. By using a property you can provide this access. As you mention you may want to perform operations before the field is accessed (lazy loading, e.g.). You have a lot of code in there that just isn't necessary anymore unless you're still working in .Net 2.0-.
I have the simple class using auto-implemented properies:
Public Class foo
{
public foo() { }
public string BarName {get; set;}
}
I obviously use the variable BarName throughout my class and now need to add logic when the property value is set (it must be all upper case, go figure). Does this mean that I need to now create a private variable for BarName , e.g. _BarName, and change the current BarName variable used throughout my class to _BarName?
Public Class foo
{
public foo() {}
private string _BarName = "";
public string BarName
{
get {return _BarName;}
set {_BarName = Value.ToString().ToUpper();}
}
}
I am trying to make sure I understand the implications of using auto-implemented properties, and what it will entail down the road when/if I need to change something. I am assuming that the refactoring, as shown above, is not a breaking change because the property is basically staying the same; it just took a little work inside the class to keep it that way and add the needed logic.
Another example, which may be more meaningful is that I need to call some method when a setter or getter is used; more then changing the value.
This seems a fair trade off the the lines and lines of code to setup properties.
Does this mean that I need to now
create a private variable for BarName
Yes
and change the current BarName
variable used throughout my class
Do not change the rest of the code in your class to use the new private variable you create. BarName, as a property, is intended to hide the private variable (among other things), for the purpose of avoiding the sweeping changes you contemplate to the rest of your code.
I am assuming that the refactoring, as
shown above, is not a breaking change
because the property is basically
staying the same; it just took a
little work to keep it that way and
add the needed logic.
Correct.
You don't need to change anything. Auto-implemented properties are just syntactic sugar. The compiler is generating the private variable and get/set logic for you, behind the scenes. If you add your own getter/setter logic the compiler will use your code instead of its auto-generated code, but as far as the users of that property are concerned, nothing has changed; any code referencing your property will continue to work.
When using automatic properties you don't get direct access to the underlying "backing" variable and you don't get access to the actual logic that gets implemented in the property getter and setter. You only have access to the property (hence using BarName throughout your code).
If you now need to implement specific logic in the setter, you can no longer use automatic properties and need to implement the property in the "old fashioned" way. In this case, you would need to implement your own private backing variable (the preferred method, at least for me, is to name the private backing variable the same name as the property, but with an initial lowercase (in this case, the backing variable would be named barName). You would then implement the appropriate logic in the getter/setter.
In your example, you are correct that it is not a breaking change. This type of refactoring (moving from automatic properties to "normal" properties should never be a breaking change as you aren't changing the public interface (the name or accessibility of the public property).
Don't use automatic properties if you know that you are going to validate that object. These objects can be domain objects etc. Like if you have a Customer class then use private variables because you might need to validate the name, birthdate etc. But if you are using a Rss class then it will be okay to just use the automatic properties since there is no validation being perform and the class is just used to hold some data.
You are correct about the refactoring and it really shouldn't break anything.
Whether or not you actually need to go through the references within the class to the property name and change those to refer to the private field would depend on whether the internal code needed to access the underlying representation of the data rather than how it was presented to consumers of the class. In most cases you could leave well enough alone.
In your simple example it would be wise to leave well enough alone and ensure that no code internal to the class could subvert the conversion/formatting being performed in the setter.
If on the other hand the getter was doing some magic to change the internal representation of the field into the way consumers needed to view the data then perhaps (in some cases) the internal code within the class would need to access the field.
You would need to look at each occurrence of the access to the auto-property in the class and decide whether it should be touching the field or using the property.
Automatic properties are just syntactic sugar, the compiler in fact creates the private member for it, but since it's generated at compile time, you cannot access it.
And later on, if you want to implement getters and setters for the property, only then you create a explicit private member for it and add the logic.