Class internal usage of public properties - c#

Let's say I have a class that exposes one property. Is it considered to be a good aproach to use the private "holder variable" for internal use in the class? Or should I use the property for internal use also.
To explain, should I use:
public class foo
{
String _statusHolder;
public String myStaus
{
get { return _statusHolder; }
set{ _statusHolder = value; }
}
public void DisplayMyStatus()
{
Console.WriteLine(_statusHolder);
}
}
Or:
public class foo
{
String _statusHolder;
public String myStaus
{
get { return _statusHolder; }
set{ _statusHolder = value; }
}
public void DisplayMyStatus()
{
Console.WriteLine(myStaus);
}
}
I could see it as beeing more consistent and more readable to use the second approach. It would also be more effective if I would later do some modificatins in the set-statement. But are there any performance issues or is it considered bad-practise for some reason?
EDIT:
It seems that everybody is leaning towards using the property internally. My initial thoughts was the same, but as a novice programmer, you can never know.
Thanks everyone for the quick feedback!

Performance issues should be negligable, as the JITer or compiler will happily work out that your function call (the getter of the property) doesn't do anything exciting, and can be inlined.
The benefit is future changes to business logic that might be put in the getter, which your class will then automatically take advantage of, without refactoring too much.
Of course, the downside is, you might want to avoid that new business logic in some circumstances, so it is something that needs to be considered based on how likely a) logic will change, and b) that logic might need to be circumvented.
The other (potential) advantage of using the property internally is that you can easily move to, or from, automatic properties.

I tend to go with calling the properties cause once stuff gets tricky you can put in locking and business logic in the getter
For C# 3.0 I would go with something along these lines (and only explicitly create the backing field when its really needed)
public class foo
{
public String Status
{
get;
set;
}
public void DisplayMyStatus()
{
Console.WriteLine(Status);
}
}

Use the property if there is one. A property can have side effects like lazy initializing that you want to have regardless from where you access the variable.
Even if the property has no side effects now, other developers could add them later, and the places where the "raw" variable is used may be error-prone because the new code is not called.
And lastly, the property makes refactoring easier, for example, when the value later is no longer stored in a variable but is calculated inside the property accessor or comes from some other source variable.

Programming in Java, I prefer using the getter method because I can put a breakpoint there and/or see changes to it in logging output.

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.

Is it possible to declare a field somehow local to its property [duplicate]

I'm using .NET 2.0 so do not have access to automatic properties. So I must resort to the following way of coding private variables and public properties
private string m_hello = null;
public string Hello
{
get{return m_hello;}
set{m_hello = value;}
}
For methods of the containing class of the above private/public members, is there anyway to restrict access to the private variable? I do not like that I can either use m_hello or Hello.
Thanks.
As others have suggested this should be an answer...
You can still use automatic properties in C# 3 when targeting .NET 2.0, along with quite a few other C# 3 features. Unlike (say) expression trees, automatic properties don't need anything special from the CLR or the framework, beyond the [CompilerGenerated] attribute (which was introduced in .NET 2.0).
So if you're using VS2008 or VS2010, then it would be worth using an automatic property.
For what it's worth though, I'd like this ability too. I'd like to be able to scope variables within a property:
public string Name
{
private string name;
get { return name; }
set { name = value; }
}
I view this a bit like making a private variable readonly - it makes no difference to clients, but it helps to enforce correctness within the class code itself.
You can accomplish this via inheritance:
abstract class A // A is not instantiatable due to being abstract
{
private string m_hello = null;
public string Hello
{
get{return m_hello;}
set{m_hello = value;}
}
}
class B : A
{
// B now cannot access the private variable, use B in your code instead of A
}
I am not claiming that this is good. Just that it can be done.
No there is not a way to do that, other than to simply follow your own convention and do this.Hello if you really need to go through your public property.
I don't see why you would need/want to do this either, as since it is your internal class, you are the one in control of the code and you can define what/how it is used, so there shouldn't be an issue.
No. Any method inside the class will have access to both.
Your team should standardize on which to use (Property or private variable).
Once you decide which to use, you could try to use a custom FxCop rule to enforce the standard.
No, basically. Well, you could do something with compiler warnings via [Obsolete] and #pragma, but that would be excessive.
You could probably do it with tooling, but eventually you need to trust people not to do stupid things. After all, do you have special rules about:
while(true) { }
or do you just put that down to "don't be stupid"? ;p
You should only access the property through the public Hello property. This is the reason for this pattern. If you add any functionality to the get or set, if you are accessing the private instance, you will introduce bugs into your code. But the anwer is NO, you cannot prevent someone from calling the Private when they are inside your class changing your code.
Personally, I see nothing wrong with accessing the private member within the class. In fact that's what I typically do (unless there's logic within the property getter/setter that I always want to leverage).
It just makes sense to me: the code within the class constitutes that class's implementation; why hide an implementation from itself?
Here's an example of what I mean. Suppose I have some member, m_denominator, and I want it never to be zero:
private int m_denominator = 1;
public int Denominator
{
get { return m_denominator; }
set
{
if (value == 0)
throw new ArgumentException("Denominator must not be zero.");
m_denominator = value;
}
}
I might say to myself: "OK, everywhere I set this value within this class, I should use Denominator to make sure I'm not setting it to zero." But I'm completely in control of what I'm setting Denominator to -- I'm inside the class! In this scenario, the point of the logic in the Denominator property is to protect the class from invalid values set by client code. There's no excuse for setting your internal state to some invalid value within the implementation of a class itself.
Of course this is not an absolute rule. There are surely times when using the property for its logic within a class may be a sensible choice as a protective measure; really, I'm just arguing that it's not wrong to access private members from within a class.
If you find yourself wanting to hide details from yourself, that may be a code smell that your class has too many responsibilities. Consider extracting one of the responsibilities into a new class.
I believe in C#10, or at least a proposal for it, you can use semi-auto properties.
We can now use the field keyword in place of a backing property field.
So this:
private int _theNumber;
public int TheNumber
{
get => _theNumber;
set => _theNumber = value;
}
Becomes this:
public int TheNumber
{
get => field;
set => field = value;
}
Granted in the example I provided an auto property would make more sense, but I wanted to show a simple example.

Blocking access to private member variables? Force use of public properties?

I'm using .NET 2.0 so do not have access to automatic properties. So I must resort to the following way of coding private variables and public properties
private string m_hello = null;
public string Hello
{
get{return m_hello;}
set{m_hello = value;}
}
For methods of the containing class of the above private/public members, is there anyway to restrict access to the private variable? I do not like that I can either use m_hello or Hello.
Thanks.
As others have suggested this should be an answer...
You can still use automatic properties in C# 3 when targeting .NET 2.0, along with quite a few other C# 3 features. Unlike (say) expression trees, automatic properties don't need anything special from the CLR or the framework, beyond the [CompilerGenerated] attribute (which was introduced in .NET 2.0).
So if you're using VS2008 or VS2010, then it would be worth using an automatic property.
For what it's worth though, I'd like this ability too. I'd like to be able to scope variables within a property:
public string Name
{
private string name;
get { return name; }
set { name = value; }
}
I view this a bit like making a private variable readonly - it makes no difference to clients, but it helps to enforce correctness within the class code itself.
You can accomplish this via inheritance:
abstract class A // A is not instantiatable due to being abstract
{
private string m_hello = null;
public string Hello
{
get{return m_hello;}
set{m_hello = value;}
}
}
class B : A
{
// B now cannot access the private variable, use B in your code instead of A
}
I am not claiming that this is good. Just that it can be done.
No there is not a way to do that, other than to simply follow your own convention and do this.Hello if you really need to go through your public property.
I don't see why you would need/want to do this either, as since it is your internal class, you are the one in control of the code and you can define what/how it is used, so there shouldn't be an issue.
No. Any method inside the class will have access to both.
Your team should standardize on which to use (Property or private variable).
Once you decide which to use, you could try to use a custom FxCop rule to enforce the standard.
No, basically. Well, you could do something with compiler warnings via [Obsolete] and #pragma, but that would be excessive.
You could probably do it with tooling, but eventually you need to trust people not to do stupid things. After all, do you have special rules about:
while(true) { }
or do you just put that down to "don't be stupid"? ;p
You should only access the property through the public Hello property. This is the reason for this pattern. If you add any functionality to the get or set, if you are accessing the private instance, you will introduce bugs into your code. But the anwer is NO, you cannot prevent someone from calling the Private when they are inside your class changing your code.
Personally, I see nothing wrong with accessing the private member within the class. In fact that's what I typically do (unless there's logic within the property getter/setter that I always want to leverage).
It just makes sense to me: the code within the class constitutes that class's implementation; why hide an implementation from itself?
Here's an example of what I mean. Suppose I have some member, m_denominator, and I want it never to be zero:
private int m_denominator = 1;
public int Denominator
{
get { return m_denominator; }
set
{
if (value == 0)
throw new ArgumentException("Denominator must not be zero.");
m_denominator = value;
}
}
I might say to myself: "OK, everywhere I set this value within this class, I should use Denominator to make sure I'm not setting it to zero." But I'm completely in control of what I'm setting Denominator to -- I'm inside the class! In this scenario, the point of the logic in the Denominator property is to protect the class from invalid values set by client code. There's no excuse for setting your internal state to some invalid value within the implementation of a class itself.
Of course this is not an absolute rule. There are surely times when using the property for its logic within a class may be a sensible choice as a protective measure; really, I'm just arguing that it's not wrong to access private members from within a class.
If you find yourself wanting to hide details from yourself, that may be a code smell that your class has too many responsibilities. Consider extracting one of the responsibilities into a new class.
I believe in C#10, or at least a proposal for it, you can use semi-auto properties.
We can now use the field keyword in place of a backing property field.
So this:
private int _theNumber;
public int TheNumber
{
get => _theNumber;
set => _theNumber = value;
}
Becomes this:
public int TheNumber
{
get => field;
set => field = value;
}
Granted in the example I provided an auto property would make more sense, but I wanted to show a simple example.

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