Why have private fields in data contracts modified through public ones? - c#

When you make a new WCF project, sample service is generated for you. The default data contract is (I've just changed the string type field title):
[DataContract]
public class CompositeType
{
bool boolValue = true;
string name = "";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string Name
{
get { return name; }
set { name = value; }
}
}
What is the point of having those private fields boolValue and name? Is it a good practice writing some data sanitizing or some other manipulations in contract, thus bloating it? It seems the only sane reason for me not writing to fields directly. So is it a bloatware or it has some reason behind it?

In my opinion, DataContracts singular purpose should be to transfer data between domains. Validation/sanitizing logic should be outside the DataContract's responsibilities. Especially if the intent is to share/link the code file in multiple projects/platforms for reuse.
This also implies that you shouldn't have your DataContract object used elsewhere in your application. It should go through some kind of adapter or converter to read/write the content to your application-specific objects. Its in that conversion (or your application objects) where you can do some validation. The simpler your data-transfer layer the better.
Plausibly, you might add logging/debugging code in the setters/getters (preferably temporarily) to track data input/output as needed. So far, that's the only case I've felt OK to put anything other than simple properties in a DataContract object (and again, I only did so temporarily).
EDIT: As to why this is the default generated file, I'm not sure. My DataContract objects are always using automatic properties. I'd suggest maybe this was a throwback to .NET 2.0 before automatic properties were introduced, but WCF/DataContracts weren't introduced until 3.0 anyway.

The same reason you ever write a getter and setter for any private value, to help aid encapsulation and allow you to manipulate the inner workings of your class without having to worry about outside members breaking since they were manipulating variables directly.

The short answer is that the public properties allow you, the designer, to restrict the values before they can be assigned to your private fields, potentially saving you from dealing with unexpected data. Although most get and set methods are the same, they are frequently the first line of defense against bad data.

Related

Is there any reason to use field over automatic property? [duplicate]

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.

DTOs. Properties or fields?

I need to create some DTO classes to transport our business objects across WCF.
Since these are just bags of data with no functionality, is there any reason I can't just use fields, or is there some good reason to expose them properly as properties?
//fields
[DataContract]
class CustomerDTO
{
[DataMember] public int Id;
[DataMember] public string Name;
}
//or properties?
[DataContract]
class CustomerDTO
{
[DataMember] public int Id { get; set; }
[DataMember] public string Name { get; set; }
}
I mostly favour immutable DTOs with read-only fields if I can get away with it:
public class CustomerDTO
{
public CustomerDTO(int id, string name)
{
Id = id;
Name = name;
}
public readonly int Id;
public readonly string Name;
// Override Equals and GetHashCode as well...
}
There's lots of advantages to be had from immutable records, such as structural equality, which makes automated test assertions much simpler to write. It also dispenses with the need to write and maintain separate Test Data Builders.
It depends on the serializer, though. JSON.NET can handle immutable records, but many other serializers can't.
For those that handle public fields, I prefer fields over properties, simply because it's more honest; automatically implemented read/write properties provide no encapsulation.
Some serializers insist on public properties, and don't serialize fields. If that's the scenario, you have to go with that.
Honestly, considering how much thought I've put into this, it's not really something that keeps me awake at night, because ultimately, at the boundaries, applications aren't object-oriented. Thus, the rules of OOD don't really apply to DTOs anyway.
Since these are just bags of data with no functionality, is there any reason I can't just use fields
There are no strong arguments against public fields here. But do realize that it is only because there is no logic (behaviour) inside the DTOs so that the normal argument of encapsulation doesn't hold.
I would still prefer properties but they're not really necessary here.
You can use either. Since it doesn't affect performance, you'd be safer off going with properties in case you run into some serialization framework or similar that doesn't work with public fields.
Note that WCF proxy generation will create those DTOs on the client side with public properties and their backing private fields, even if you use public fields on the service side. If you somehow don't want that, you need to share a DTO library between the service and the client.
The DataMember attribute will work with both public fields and properties, so either would be possible. However, I would recommend sticking with properties.
In particular, if you are using StyleCop, then you would be breaking rule SA1401.
The reason for this rule's existence doesn't really apply in your case, but it would still be a maintenance problem if you are running StyleCop validation as part of a build on a continuous integration server.
Here are two advantages of properties over fields that I didn't see anyone else mention.
Friction in syntax properly matches capabilities
I think the default behavior should be the safer option. For fields, the default behavior allows for mutability, which is the more dangerous option. The keyword readonly must be added to make a field immutable (outside of constructors). In contrast, the default state of an auto property is immutable; the syntax set; must be added in order for the property to be mutable (outside of constructors).
Reference count given in Visual Studio's Code Lens
Unlike a field, viewing a property in Visual Studio has a "Code Lens", which includes its reference count. I am able to understand and refactor a property more quickly than a field because of this additional information. Of course, one can search in Visual Studio for references to things like fields and properties using Shift+F12, but that is an extra step that takes time. Moreover, in rare cases, some projects include multiple targets. This makes the Shift+F12 search results more difficult to use because there is a search is performed for every target. In contract, the reference count given in a property's Code Len is independent of the number of project targets.
Conclusion
To directly answer the question though, I prefer to use mutable properties (and no explicit constructors) in order to ensure I will be using the happiest of happy paths in the serialization library (which was mentioned in the answer of #ErenErsönmez).
I'd never expose fields directly, most companies prohibit this in their standards. Effectively you totally throw away encapsulation. DTOs, being anemic representations of something more complex are an odd case as their properties pretty much break encapsulation anyway. Personally, I'd use the properties as that's what they're there for. It also lets you implement "dirty" functionality etc. if you need to which isn't so easy if you're tweaking fields directly.

Why use private members then use public properties to set them?

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-.

How should I design my object model so that my DAL can populate read-only fields?

In order to separate concerns, on my current project, I've decided to completely separate my DAL and BLL/Business objects in separate assemblies. I would like to keep my business objects as simple structures without any logic to keep things extremely simple. I would like if I could keep my Business Logic separate from my DAL also. So my application will tell my DAL to load my objects, my DAL will run off to the database and get the data, populate the object with the data and then pass it back to my BLL.
Question - how can I have my DAL in a separate assembly and push data into the read only fields?
If I set the getter as protected then inherited objects can access it which isn't really what I want as I'd be returning the inherited object types, not the original object types.
If I set the getter as internal, then my DAL must reside in the same assembly as my BLL which I don't want.
If I set the getter as public, then anyone can read/write to it when it should be read only.
Edit: I note that I can have a return type of ObjectBase but actually be returning an object or collection of objects that are derived form ObjectBase so to the outside world (outside my DAL) the properties would be read-only, but my derived types (only accessible inside my DAL) the properties are actually read/write.
You can set the read only property via a constructor.
This is a situation without a silver-bullet; the simplest options are limited or don't meet your requirements and the thorough solutions either begin to have smells or begin to veer away from simplicity.
Perhaps the simplest option is one that I haven't seen mentioned here: keeping the fields / properties private and passing them as out / ByRef parameters to the DAL. While it wouldn't work for large numbers of fields it would be simple for a small number.
(I haven't tested it, but I think it's worth exploring).
public class MyObject()
{
private int _Id;
public int Id { get { return _Id; } } // Read-only
public string Name { get; set; }
// This method is essentially a more descriptive constructor, using the repository pattern for seperation of Domain and Persistance
public static MyObject GetObjectFromRepo(IRepository repo)
{
MyObject result = new MyObject();
return repo.BuildObject(result, out _Id);
}
}
public class MyRepo : IRepository
{
public MyObject BuildObject(MyObject objectShell, out int id)
{
string objectName;
int objectId;
// Retrieve the Name and Value properties
objectName = "Name from Database";
objectId = 42;
//
objectShell.Name = objectName;
Console.WriteLine(objectShell.Id); // <-- 0, as it hasn't been set yet
id = objectId; // Setting this out parameter indirectly updates the value in the resulting object
Console.WriteLine(objectShell.Id); // <-- Should now be 42
}
}
It's also worth noting that trying to keep your domain / business objects to the bare-minimum can involve more than you think. If you intend to databind to them then you'll need to implement IPropertyNotifyChanged, which prevents you from using automatically-implemented properties. You should be able to keep it fairly clean, but you will have to make some sacrifices for basic functionality.
This keeps your SoC model nicely, it doesn't add in too much complexity, it prevents writing to read-only fields and you could use a very similar model for serialization concerns. Your read-only fields can still be written to by your DAL, as could your serializer if used in a similar fashion - it means that conscious effort must be taken by a developer to write to a read-only field which prevents unintentional misuse.
Model Project
namespace Model
{
public class DataObject
{
public int id { get; protected set; }
public string name { get; set; }
}
}
Data Project
namespace Data
{
class DALDataObject : DataObject
{
public DALDataObject(int id, string name)
{
this.id = id;
this.name = name;
}
}
public class Connector
{
public static DataObject LoadDataObject(int objectId)
{
return new DALDataObject(objectId, string.Format("Dummy object {0}", objectId));
}
public static IEnumerable<DataObject> LoadDataObjects(int startRange, int endRange)
{
var list = new List<DataObject>();
for (var i = startRange; i < endRange; i++)
list.Add(new DALDataObject(i, string.Format("Dummy object {0}", i)));
return list;
}
}
}
How about just live with it?
Implement with those guidelines, but don't add such a hard constraint in your model. Lets say you do so, but then come another req where you need to serialize it or do something else, and then you are tied with it.
As you said in other comment, you want pieces that are interchangeable ... so, basically you don't want something that's tied into specific relations.
Update 1: Perhaps "just live with it" was too simplistic, but I still have to stress out that you shouldn't go too deep into these things. Using simple guidelines, keeping your code clean and SOLID its the best you can do at the beginning. It won't get in the way of progress while refactoring when everything is more settled isn't hard.
Make no mistake, I am not at all a person that goes writing code without any thinking on it. But, I have gone with such approaches and only in a handful cases they pay off --- without any indication that you wouldn't have a similar result by going simple and evolving it.
IMHO this one does not fit into important architecture concerns that need to be addressed at the very beginning.
Pre-emptive follow up: beware if you can't trust your team into following simple guidelines. Also make sure to begin with some structure, pick a couple scenarios that set a structure in with real stuff, the team will know their way much better when there is something simple there.
In my opinion, the best way to handle this is to have the business objects and the DAL in the same assembly separated by namespace. This separates the concerns logically and allows you to use internal setters. I can't think of any benefit to separating them into their own assemblies because one is useless without the other.

C# Automatic Properties

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

Categories