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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between a field and a property in C#
I'm a beginning programmer and I've read all about class properties. Books state that properties allow you to indirectly access member variables. Ok, so what makes it any different than just making the field public and accessing it directly?
Here's a quote from Learning C# 3.0 by Jesse Liberty:
For example, you might want external
classes to be able to read a value, but not change it; or you might want to write
some code so that the internal field can accept only values in a certain range. If you
grant external classes free access to your member fields, you can’t control any of that.
I don't understand what he is saying here. Can someone further explain this or give an example of why I would want to use a property over making the field public. As I understand it now they would both accomplish the same exact thing...so I'm obviously missing something here.
The other answers provided so far provide details of the advantages of accessor/mutator logic, but all seem to miss out on the ideological point about object encapsulation.
You see, class member fields are an implementation detail. If you have a class that represents a collection, for example, then you could implement it as a linked list (and expose the root-node via a public field) or you could implement it as a resizable array and expose the index0 member.
The problem with revealing implementation details is that you lose any kind of defined interface between your class and its consumers. By ensuring all operations are done via defined methods (controlled by the class itself) you make it easier to work with and provide for a long-term viewpoint. For example, you are far more easily able to convert your collection implementation from one type (the linked-list) to another (the array) without breaking any contracts with your class' consumers.
Don't worry about any performance impact of trivial accessor/mutator methods: the JIT compiler will inline the property methods. If you'll run some benchmarks you'll see the performance of properties vs fields is identical.
He's saying that properties can provide a getter but not a setter, therefore making them read-only (for example)
Properties are just syntactic sugar for a method e.g.
public int SomeProperty { get; set; }
is just sugar for
private int _someProperty;
public int SomeProperty_get()
{
return _someProperty;
}
public void SomeProperty_set(int value)
{
_someProperty = value;
}
This means that property setters/getters can apply logic that a mere public field can't
Edit: I'm not exactly sure what field names the CLR gives the backing fields for auto-properties - it's just an example :)
Edit2:
An example of a read only property:
public int SomeProperty { get; }
and finally a public read - private write (for autoproperties)
public int SomeProperty { get; private set; }
Really useful when you can't be bothered to type a backing field in :)
Just remember, if there is a possibility that you wish to apply logic to a member, then a property is the way to go. This is the way a lot of frameworks work (e.g. tracking 'dirty' objects by using a property to tell some sort of object manager that something has changed, this would not be possible using a public field)
Properties can have side-effects, They provide syntactic sugar around 'getter' and 'setter' methods.
public class MyClass {
int sizeValue = 0;
public int Size {
get {
return sizeValue;
}
set {
if ( value < 10 ) throw new Exception("Size too small");
sizeValue = value;
}
}
}
Properties can also have different levels of protection for get and set, you cannot do that with fields.
public class MyOtherClass {
// only this object can set this.
public int Level {
get; private set;
}
// only things in the same assembly can set this.
public string Name {
get; internal set;
}
}
There are a number of important differences between "properties" and "member access".
The most significant is that you can, through a property, make a member read-only (you can access the state, but you cannot change it). Just like "getter()" and "setter()" methods in Java.
You can also return a computed value from a property (generate a value "on-the-fly", as though it were a variable).
Properties can be configured so that:
they are read-only, Public MyProp {get;}
they are write-only Public MyProp {set;}
they are readable by external objects, but can only be set by the class's internals
Public MyProp {get; private set;}
As others have posted, you can also put logic into your getters and setters. For example before allowing the property to bet set to a new value, you can check that the value is acceptable.
You cannot do any of that with a public field.
Basically, a public field is the dumbest sort of property that you can have. Given that .Net now allows autobacking fields for your properties. There is no good reason to use public fields any longer.
If you have Public Int MyAge
I can set it to -200 or 20,000 and there is nothing you can do about it.
If you use a property you can check that age is between 0 and 150, for example.
Edit: as per IanNorton's example (man, that was fast)
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;
my question is simple, is using the get set properties of C# considered good, better even than writing getter and setter methods? When you use these properties, don't you have to declare your class data members as public ? I ask this because my professor stated that data members should never be declared as public, as it is considered bad practice.
This....
class GetSetExample
{
public int someInt { get; set; }
}
vs This...
class NonGetSetExample
{
private int someInt;
}
Edit:
Thanks to all of you! All of your answers helped me out, and I appropriately up-voted your answers.
This:
class GetSetExample
{
public int someInt { get; set; }
}
is really the same as this:
class GetSetExample
{
private int _someInt;
public int someInt {
get { return _someInt; }
set { _someInt = value; }
}
}
The get; set; syntax is just a convenient shorthand for this that you can use when the getter and setter don't do anything special.
Thus, you are not exposing a public member, you are defining a private member and providing get/set methods to access it.
Yes, members should normally never be declared public in good design for several reasons. Think about OOP where you inherit the class later. Kind of hard to override a field. :-) Also it prevents you from keeping your internals from being accessed directly.
The simplistic get; set; design was introduced in C# 2.0. It's basically the same as declaring everything with a private member backing it (decompile it out in tool like Reflector and see).
public int someInt{get;set;}
is directly equal to
private int m_someInt;
public int someInt{
get { return m_someInt; }
set { m_someInt = value; }
}
The great part about having the simplified getter/setter is that when you want to fill in the implementation with a little bit more guts later, you do not break ABI compatibility.
Don't worry about getter/setters slowing down your code through indirection. The JIT has a thing called inlineing makes using the getter/setter just as efficient as direct field access.
Yes. Data members should be private and automatic properties allow it and give public access on right way.
But you should be careful. Understand the context is very important. In threaded application, update one property following an another related property can be harmful to consistency. In that case, a setter method updating the two private data members in a proper way makes more sense.
In your first example C# automatically generates the private backing fields so technically the data member is not declared as public only the getter/setter.
because with public data member , that data member can be changed or can be read out of class
and you cannot control read/write operation accessibility but with properties you can control
read/write stream for example consider this statement :
public MyVar{private get; public set;}
means value of MyVar can be changed only inside of class and can be read out of class(read privately and read publicly) and this is not possible with just public data members
In a "pure" object oriented approach, it is not considered OK to expose the state of your objects at all, and this appliese to properties as they are implemented in .NET and get_ set_ properteis of Java/EJB. The idea is that by exposing the state of your object, you are creating external dependencies to the internal data representation of your object. A pure object design reduces all interactions to messages with parameters.
Back to the real world: if you try to implement such a strict theoretical approach on the job, you will either be laughed out of the office or beaten to a pulp. Properties are immensely popular because they are a reasonable compromise between a pure object design and fully exposed private data.
It's quite reasonable, and your professor (without context) is wrong. But anyway, using "automatic properties", is fine, and you can do it whether they are public or private.
Though in my experience, whenever I use one, I almost inevitably end up needing to write some logic in there, and hence can't use the auto props.
your professor was quite right.
Consider this trivial example of why "getters" should be avoided: There may be 1,000 calls to a getX() method in your program, and every one of those calls assumes that the return value is a particular type. The return value of getX() may be sotred in a local variable, for example, and the variable type must match the return-value type. If you need to change the way that the object is implemented in such a way that the type of X changes, you're in deep trouble. If X used to be an int, but now has to be a long, you'll now get 1,000 compile errors. If you fix the problem incorrectly by casting the return value to int, the code will compile cleanly but won't work. (The return value may be truncated.) You have to modify the code surrounding every one of those 1,000 calls to compensate for the change. I, at least, don't want to do that much work.
Holub On Patterns
I'm a bit confused on the point of Automatic properties in C# e.g
public string Forename{ get; set; }
I get that you are saving code by not having to declare a private variable, but what's the point of a property when you are not using any get or set logic? Why not just use
public string Forename;
I'm not sure what the difference between these 2 statements is, I always thought you used properties if you wanted additional get/set logic?
Properties can have code put into them without breaking contract, fields can't have code put into them without changing them to properties (and breaking the interface). Properties can be read only or write only, fields can't. Properties can be data bound, fields can't.
You can write
public string Forename{ get; private set; }
to get read-only properties... Still not nearly as versatile as real properties, but it's a compromise that for some works.
I'm not sure what the difference between these 2 statements is, I always thought you used properties if you wanted additional get/set logic?
In the first case, the compiler will automatically add a field for you, and wrap the property. It's basically the equivalent to doing:
private string forename;
public string Forename
{
get
{
return this.forename;
}
set
{
this.forename = value;
}
}
There are many advantages to using properties over fields. Even if you don't need some of the specific reasons, such as databinding, this helps to future-proof your API.
The main problem is that, if you make a field, but in v2 of your application, need a property, you'll break the API. By using an automatic property up front, you have the potential to change your API at any time, with no worry about source or binary compatibility issues.
It is meant that you expect to add the logic later.
If you do so and have it as property from the beginning, you will not have to rebuild the dependent code. If you change it from a variable to a property, then you will have to.
Consider looking at some related threads about Difference Between Automatic Properties and Public Fields, Fields vs Properties, Automatic Properties - Useful or Not?, Why Not to Use Public Fields.
Public data members are evil (in that the object doesn't control modification of it's own state - It becomes a global variable). Breaks encapsulation - a tenet of OOP.
Automatic properties are there to provide encapsulation and avoid drudgery of writing boiler plate code for simple properties.
public string ID { get; set;}
You can change automatic properties to non-automatic properties in the future (e.g. you have some validation in a setter for example)... and not break existing clients.
string m_ID;
public string ID
{
get { return m_ID; }
set
{
//validate value conforms to a certain pattern via a regex match
m_ID = value;
}
}
You cannot do the same with public data attributes. Changing a data attribute to a property will force existing clients to recompile before they can interact again.
When adding auto properties the compiler will add get set logic into the application, this means that if you later add to this logic, and references to your property from external libraries will still work.
If you migrated from a public variable to a property, this would be a breaking change for other libraries that reference yours - hence, why not start with an auto property? :)
For one, you can set the property to virtual and implement logic in an inheriting class.
You can also implement logic in the same class afterwards and there won't be side-effects on any code relying on the class.
Not all properties need get/set logic. If they do, you use a private variable.
For example, in a MV-something pattern, your model would not have much logic. But you can mix and match as needed.
If you were to use a field like you suggested in place of a property, you can't for example define an interface to describe your class correctly, since interfaces cannot contain data fields.
A property is like a contract, and you can change the implemenation of a property without affecting the clients using your classes and properties. You may not have any logic today, but as business requirements change and if you want to introduce any code, properties are your safest bet. The following 2 links are excellent c# video tutorials. The first one explains the need of properties over just using fields and the second video explains different types of properties. I found them very useful.
Need for the Properties in C#
Poperties in C#, Read Only, Write Only, Read/Write, Auto Implemented
Take a look at the following code and explanation.
The most common implementation for a property is getter or a setter that simply reads and writes to a private field of the same type as a property. An automatic property declaration instructs the compiler to provide this implementation. The compiler automatically generates a private backing field.
Look into the following code:-
public class Stock
{
decimal currentPrice ; // private backing field.
public decimal CurrentPrice
{
get { return currentPrice ; }
set { currentPrice = value ; }
}
}
The same code can be rewritten as :-
public class Stock
{
public decimal CurrentPrice { get ; set ; } // The compiler will auto generate a backing field.
}
SOURCE:- C# in a Nutshell