The semantic difference between a property and a field, and their implications - c#

Take private string Property {get; set;} versus private string field.
Note that both are private (so they will not be exposed outside of this class) and that the property is not employing extra validation.
As regards semantics, do they have different meanings? In the sense that, are they interchangeable when used like this?
And when it comes to implications, such as (micro?) performance, does it matter if you create a field versus a property i.e. letting the compiler take care of the backing field for you.

When they're private the only difference I know is that the property is not suitable for out and ref parameters.
But mostly a private property does not deliver any advantages (over a field), so why bother?
There probably are (micro) performance costs. I would worry more about the extra clutter.

A property is about data hiding of a field
A private property does not mean much, since whoever has access to the property, will have access to the field as well
There is no performance implication for auto-property versus backing field since compiler spits out the backing field but there can be serialisation/deserialisation caveats.
UPDATE
Performance implications:
There is a slight performance in using property (auto or with backing field) vs field since a property is a method and a CLR virtcall needs to be called.
But as I said, there is not much point in using property and I believe a field is more readable as usually immediately visible by the naming convention (starting with underscore or camel casing).

You can't have a reference to a property, but you can get a reference to a member. Thus, if you use members, you might have trouble switching them to properties for whatever reason later, such as adding the notorious validation.

Creating a private automatic property has no use that I can see. If its not automatic it could be used as some kind of internal 'event handler' to keep the object state up to date: perform some actions every time the field changes (through the setter) anywhere in the code.
Performance? I dont think there would be an issue, not even at a micro micro level.

Properties ARE functions.
Fields are 'variables with at least class visibility'.
So if you have private property vs private field:
The difference from the performance point:
no difference if you use optimization and no trace (properties are treated as inlines).
The difference in semantics:
1) Formally no difference.
2) More deeply, there IS a difference. Since properties are functions you CAN get a delegate from getter and setter. And CAN use the delegate as... delegate, like putting this delegate to the list with other delegates (Create a delegate from a property getter or setter method)
The difference from a design view:
But properties are functions that looks like variables. Why one could need functions that look like variables?
Lets say you have class Hand and this hand has variable fingersNumber.
class Hand
{
public int fingersNumber;
}
Then you may have a lot of code like
if(he is BadPerson) leftHand.fingersNumber--
if(doctor.Heal()) leftHand.fingersNumber++
But at some point you may want to add some other variable to Hand. Lets say it is ringsNumber. And you know, that you can't have more than 10 rings for each finger.
class Hand
{
public int fingersNumber;
public int ringsNumber;
}
now, you cannot just do
leftHand.fingersNumber--
because you have to control ringsNumber on fingersNumber dependence.
So you have to create some functions that whould check this dependance. Also you have to hide fingersNumber ander ringsNumber from users so they cannot change this fields without the check.
class Hand
{
private int fingersNumber;
private int ringsNumber;
public int GetFingersNumber(){...check logic...}
public void SetFingersNumber(int value){...check logic...}
public int GetRingsNumber(){...check logic...}
public void SetRingsNumber(int value){...check logic...}
}
And use this functions as
if(he is BadPerson) leftHand.SetFingersNumber(leftHand.GetFingersNumber()-1)
The problem here that the old code leftHand.fingersNumber-- would not work now. And from the beginning you wouldn't know that one will add rings in the future. To solve the problems it became a paradigm to set fields as private and use Set and Get functions to get and change variables and BE SURE that in the future one could add any logic there and code would work!
Setters and Getters is a current situation in C++, Java and many languages.
But C# creators went further and decorated such getters and setters functions as "properties".
class Hand
{
private int fingersNumber;
public int FingersNumber
{
get{return fingersNumber;}
set{fingersNumber=value;}
}
...
}
...
if(he is BadPerson) leftHand.FingersNumber--;
But most of the time people create such simple property and, you see the example, it is 5 lines of routine code. So at some version of C# autoproperties was added to simplify life of programmers. So your class is probably looks like
class Hand
{
public int FingersNumber{get;set;}
}
but at any time you can extend this get set behaviour:
class Hand
{
private int fingersNumber;
public int FingersNumber
{
get{...check logic...}
set{...check logic...}
}
...
}
And it will NOT BRAKE ANY CODE. Like
if(he is BadPerson) leftHand.FingersNumber--;
So thats what are the properties, why do they used and what is the difference with fields.
Also as I ser earlier, simple properties and autoproperties have the same performance as variables if you use optimization. Se disassembly or just google about it.

Related

What's the reason for peoples to use properties with get; set; instead of fields?

I often see properties in classes, instead of fields. It looks like that:
class TestClass
{
public ulong Id { get; set; }
public string Description { get; set; }
}
Why peoples do this? They could use fields instead. I see at least single pro there - we can pass fields with ref keyword into functions. Is there any pro for properties or other reasons to use them like that?
The main reason is encapsulation - the value can only be changed trough the corresponding properties, and this continues to be the case even if you later decide that the property shouldn't just return a value. Maybe you find that you'll want to fire an event when a value changes? If you've got a property, that's very easy. If you've got a public field, you need to make a breaking change.
In addition, properties can be virtual or declared in interfaces. And they can be declared read-only.
Oh, and it helps in debugging: You can set a breakpoint on the "set", if you want to know who is changing your value (unexpectedly).
People use properties instead of fields mainly due to coding conventions. If it doesn't perform any actual encapsulation (in case of POCO), then there's not much of a difference in C#. Most of the times fields could be used instead of properties with no consequences whatsoever.
// This:
public string MyValue;
// Could be later on changed to this:
public string MyValue { get; set; }
// With no compatibility issues.
Although it's interesting to speculate why conventions are the way they are. In C# difference between properties and fields is mostly hidden from consumer standpoint. This is not necessarily the case in older languages. I.e. in Java you had to write getter and setter methods explicitly. So if you have a field in Java, and now you decide that you want to encapsulate it, then you would need to go over all usages of that field and use getters and setters instead. This could be even a bigger issue if you use dynamic library linking (that used to be popular style of deployment some time ago). Because of this it was easier to encapsulate fields from the start, so you wouldn't have backwards compatibility issues in the future. Naturally these conventions spread to other languages as well.

Why ever use fields instead of properties?

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;

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

Is using get set properties of C# considered good practice?

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

Auto-implemented getters and setters vs. public fields

I see a lot of example code for C# classes that does this:
public class Point {
public int x { get; set; }
public int y { get; set; }
}
Or, in older code, the same with an explicit private backing value and without the new auto-implemented properties:
public class Point {
private int _x;
private int _y;
public int x {
get { return _x; }
set { _x = value; }
}
public int y {
get { return _y; }
set { _y = value; }
}
}
My question is why. Is there any functional difference between doing the above and just making these members public fields, like below?
public class Point {
public int x;
public int y;
}
To be clear, I understand the value of getters and setters when you need to do some translation of the underlying data. But in cases where you're just passing the values through, it seems needlessly verbose.
I tend to agree (that it seems needlessly verbose), although this has been an issue our team hasn't yet resolved and so our coding standards still insist on verbose properties for all classes.
Jeff Atwood dealt with this a few years ago. The most important point he retrospectively noted is that changing from a field to a property is a breaking change in your code; anything that consumes it must be recompiled to work with the new class interface, so if anything outside of your control is consuming your class you might have problems.
It's also much simpler to change it to this later:
public int x { get; private set; }
It encapsulates setting and accessing of those members. If some time from now a developer for the code needs to change logic when a member is accessed or set it can be done without changing the contract of the class.
The idea is that even if the underlying data structure needs to change, the public interface to the class won't have to be changed.
C# can treat properties and variables differently at times. For example, you can't pass properties as ref or out parameters. So if you need to change the data structure for some reason and you were using public variables and now you need to use properties, your interface will have to change and now code that accesses property x may not longer compile like it did when it was variable x:
Point pt = new Point();
if(Int32.TryParse(userInput, out pt.x))
{
Console.WriteLine("x = {0}", pt.x);
Console.WriteLine("x must be a public variable! Otherwise, this won't compile.");
}
Using properties from the start avoids this, and you can feel free to tweak the underlying implementation as much as you need to without breaking client code.
Setter and Getter enables you to add additional abstraction layer and in pure OOP you should always access the objects via the interface they are providing to the outside world ...
Consider this code, which will save you in asp.net and which it would not be possible without the level of abstraction provided by the setters and getters:
class SomeControl
{
private string _SomeProperty ;
public string SomeProperty
{
if ( _SomeProperty == null )
return (string)Session [ "SomeProperty" ] ;
else
return _SomeProperty ;
}
}
Since auto implemented getters takes the same name for the property and the actual private storage variables. How can you change it in the future? I think the point being said is that use the auto implemented instead of field so that you can change it in the future if in case you need to add logic to getter and setter.
For example:
public string x { get; set; }
and for example you already use the x a lot of times and you do not want to break your code.
How do you change the auto getter setter... for example for setter you only allow setting a valid telephone number format... how do you change the code so that only the class is to be change?
My idea is add a new private variable and add the same x getter and setter.
private string _x;
public string x {
get {return _x};
set {
if (Datetime.TryParse(value)) {
_x = value;
}
};
}
Is this what you mean by making it flexible?
Also to be considered is the effect of the change to public members when it comes to binding and serialization. Both of these often rely on public properties to retrieve and set values.
Also, you can put breakpoints on getters and setters, but you can't on fields.
AFAIK the generated CIL interface is different. If you change a public member to a property you are changing it's public interface and need to rebuild every file that uses that class. This is not necessary if you only change the implementation of the getters and setters.
Maybe just making fields public you could leads you to a more Anemic Domain Model.
Kind Regards
It is also worth noting that you can't make Auto Properties Readonly and you cannot initialise them inline. Both of these are things I would like to see in a future release of .NET, but I believe you can do neither in .NET 4.0.
The only times I use a backing field with properties these days is when my class implements INotifyPropertyChanged and I need to fire the OnPropertyChanged event when a property is changed.
Also in these situations I set the backing fields directly when values are passed in from a constructor (no need to try and fire the OnPropertyChangedEvent (which would be NULL at this time anyway), anywhere else I use the property itself.
You never know if you might not need some translation of the data later. You are prepared for that if you hide away your members. Users of your class wont notice if you add the translation since the interface remains the same.
The biggest difrence is that, if ever you change your internal structure, you can still maintain the getters and setters as is, changing their internal logic without hurting the users of your API.
If you have to change how you get x and y in this case, you could just add the properties later. This is what I find most confusing. If you use public member variables, you can easily change that to a property later on, and use private variables called _x and _y if you need to store the value internally.
why we dont just use public fields instead of using properties then
call accessors ( get,set ) when we dont need to make validations ?
A property is a member that provides a flexible mechanism to read only or write only
Properties can be overridden but fields can't be.
Adding getter and setter makes the variable a property as in working in Wpf/C#.
If it's just a public member variable, it's not accessible from XAML because it's not a property (even though its public member variable).
If it has setter and getter, then its accessible from XAML because now its a property.
Setters and getters are bad in principle (they are a bad OO smell--I'll stop short of saying they are an anti-pattern because they really are necessary sometimes).
No, there is technically no difference and when I really want to share access to an object these days, I occasionally make it public final instead of adding a getter.
The way setters and getters were "Sold" is that you might need to know that someone is getting a value or changing one--which only makes sense with primitives.
Property bag objects like DAOs, DTOs and display objects are excluded from this rule because these aren't objects in a real "OO Design" meaning of the word Object. (You don't think of "Passing Messages" to a DTO or bean--those are simply a pile of attribute/value pairs by design).

Categories