In the following setter, I can access the property backing field directly or through the getter. Is there a scenario when one would be preferred over the other?
public string Name {
get { return this.name; }
set {
if (value == this.name) return;
// or
// if (value == this.Name) return;
// ?
this.name = value;
NameChanged.Raise(this, this.name);
// or
// NameChanged.Raise(this, this.Name);
// ?
}
}
There is a related question. How would you initialize properties in the c-tor?
public MyClass(string name) { this.name = name; }
// or
public MyClass(string name) { Name = name; }
I use this.name, for the reason that at construction time the instance might be in an invalid/unstable/undefined state, so Name-setter validation might falsely fail. Any other opinions?
I would say that "Name = name" is more correct, because if you were to declare the "name" property as virtual then someone could override your property behaviour, but your constructor would still bypass their logic.
Additionally properties can encapsulate behaviour such as raising change events, which you shouldn't bypass. No user can add a handler to your event until you have constructed the object. Therefore if you make a setting in a constructor where you have external events, it won't be raised.
EDIT
See the comments below for why virtual was a bad example.
My personal approach to this problem is
Only use a this qualifier when to do otherwise would result in incorrect behavior or a compilation error.
I prefer to make my code readable in the abscence of a this qualifier. If it's unreadable without a this qualifier I strive to change the code to be readable.
In this case, the difference between the syntax is that in one case the getter/setter get invoked, while in the other case they don't. Correct?
I think it would be best to use Name rather than this.name. This way, only the getter/setter have access to the "unprotected" variable, and you can confirm any invariants about this value looking only at the getter and setter rather than at the whole class.
My personal opinion is to preferably use the property unless that results in the incorrect behaviour. What it comes down to is that using the property indicates a commitment to the semantics of your class and the design of your API.
Obviously sometimes there are going to be exceptions to this rule... sometimes the 'property' means something distinct to the value of the backing field (in your example, the property raises an event). If the internal use explicitly needs to avoid the semantics of the property (you don't want the event to fire), then the backing field is the correct 'second choice'.
On an unrelated note, for better or for worse, the Microsoft StyleCop application specifically prefers the convention of accessing private fields with the 'this' prefix to differentiate access of local variables and class fields (rather than prefixing such as '_' or 'm_' or variants thereof... which ironically are the convention used in legacy .NET framework code).
I agree with the others; you generally want to use the property. The reason for this is that you will get the logic that comes with it. In WPF, for example, if you don't use the property and instead use the field PropertyChanged events won't be fired, which means that any controls bound to that property won't get updated. Of course, you can't call the property within the property or you'll end up with a stack overflow.
That said, there are times when you would want to avoid that logic entirely, and once in a while variable initialization falls under that. In that case, you want to use the field.
Accessing the field within the property could potentially lead to an overflow if you're not careful. I always access the property to avoid those potential situations.
In the following setter, I can access property backing field directly or through the getter? Is there a scenario when one would be preferred over the other?
only use it when there is a conflict with other variables in scope
There is a related question - how do you initialize properties in the c-tor?
If you have a property, use the property
I you don't want to raise the PropertyChanged event, access the field instead of the property. However, in the constructor, you don't really care about raising that event, since you know for sure that no one has subscribed to the event yet...
My recommendation is that if you have access to the field and the field does not require special logic. An example:
private int width;
public int Width
{
get
{
return width;
}
set
{
if (value < 0)
throw new InvalidArgumentException("Mass cannot be below 0");
width = value;
}
}
In this case you would NOT want to access the field, because you (probably) cannot guarantee that the value you are setting is above 0.
However, if you have a property like:
public int Height { get; set; }
then it would probably be a good idea to access the field when possible.
Related
I have seen that get/set properties can be used in two different ways:
Without any logic:
public string PublicString { get; set; }
With logic, passing the value to backing field.
private string backingString;
public string PublicString
{
Get
{
Return backingString;
}
Set
{
If (value != “”)
{
backingString = value;
}
}
}
Questions:
if you want to perform logic, do you have a backing property or is it
possible to do PublicString = value?
if you want to return an error when you failed to set the field,
what would be the best practice for doing this?
Thanks
The short form above automatically creates a backing field for the property and a getter and setter that only return or set the value of the backing field.
If you decide to implement the getter and setter manually, you do not need to have a backing field. In fact, you can implement whichever logic you require (e.g. deriving the value from another field). However, it is common practice for property getter and setters to be lightweight as this matches the expectations of the caller. If you need a lot of logic I the property, methods are a better approach and should be named so that the communicate their purpose to the caller.
If you want to store the value somewhere, a backing field is a common approach (unless you store the value in another place). It won't work to assign the value to the property itself as you show in your example (PublicString = value) because this calls the setter again and this ends in an endless loop.
If you fail to set the value, you can communicate this to the caller by throwing an exception. However, as properties tend to be lightweight, it should not the standard scenario that properties throw exceptions. Again, if setting the property is so complicated or the signature of a property does not allow for a caller to understand how to use the property (so that the use ends in an exception), methods might be a preferred approach.
Microsoft has published the following guidelines for Property Design:
http://msdn.microsoft.com/en-us/library/ms229006.aspx
Regarding property getter/setter exceptions:
√ DO preserve the previous value if a property setter throws an exception.
X AVOID throwing exceptions from property getters.
Property getters should be simple operations and should not have any preconditions. If a getter can throw an exception, it should probably be redesigned to be a method. Notice that this rule does not apply to indexers, where we do expect exceptions as a result of validating the arguments.
If you wish to have a logic in setter, you need a backup field. Otherwise, if you would try
public int Number
{
set
{
Number = value;
}
}
it would cause a recursion when setting the property. As for the second question, throwing an exception is fine in case your co-workers or users of that library are used to fact that properties sometimes substitute behaviour of methods. Personally, I don't do that. If setting of a property can fail I typically make a method which sets the property instead and mark it with
/// <exception cref=""></exception>
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Should you access a variable within the same class via a Property?
I ran into this recently and was curious if there was some sort of standard for which one you should reference while inside a class.
I mean really it shouldn't make a difference whether you access the member variable directly or go through the property (unless you need to dodge some custom setter code), but I wanted to be sure there wasn't a best practice for it.
partial class MyClass {
private string foo;
internal string Foo {
get {
return foo;
}
private set {
foo=value;
// I do other stuff
}
}
public void DoSomething() {
//Option 1;
Foo="some string";
//Option 2;
foo="some string";
}
}
This shouldn't be a choice you really make. Either the code in the setter is supposed to run, in which case use the property, or it's not, in which case you use the member variable. In most all situations one is right and one is wrong. Neither is always right/wrong in the general case, and it's unusual for it to "not matter".
For example, if the setter code is firing a "changed" event, do you want external objects to be notified that it changed, or not? If you're changing it in response to a previous change, probably not (infinite recursion anyone?) if no, you probably want to make sure it's fired (so that you're not changing a value and not notifying anyone of changes).
If it's just validating that the value being set is valid, then either you know that, in this context, the value is already validated and must be valid, in which case there is no need to validate again; set the property. If you haven't yet validated what you're about to set then you want the validation logic to run, so use the property.
This question is quite a lot debated, so there is no obvious answer to the question.
Personally I prefer to access via the property because you might have some validation or conversion code in it. Even though your getters and setters are trivial, they might change in the future.
If you wrapped the field foo in the property Foo, you probably did so for a reason (conversion, events, validation, etc). So, generally speaking, the only place you should be referencing the field foo is in the getters and setters for the property Foo. The rest of the code should reference the property Foo.
I'm sure there exists some obscure situation where you would need to bypass the property's getters and setters, and that's certainly okay to do, but such situations would be the exception to the rule.
Option 1 is good practice. because if you use the Option 2, you will lose other stuff when setting the foo value.
I would go with Option 1. If you're setting a variable, you should use the property and not access the variable directly. This is because the property has the extra code you indicated with "// I do other stuff". You wouldn't want to have to repeat this "other stuff" just because you didn't set the property...unless, you don't want to do "other stuff" when you're setting it this time.
Honestly, this is just a theoretical situation, and it would be a lot easier to answer if you give a practical situation where you encounter this problem.
When using the INotifyPropertyChanged interface, using the property is a must, if you wish to update binded objects.
If the setter doesn't have a logic there is no point in explicitly declaring the private variable and it's better to use auto-implemented properties:
internal string Foo
{
get;
private set;
}
public void DoSomething()
{
this.Foo = "some string";
}
If the setter has a logic, the private variable should only be used in the setter and never be modified outside of the setter.
In any case (and in my opinion :)) a private variable should never appear anywhere else beside the property setter.
Imagine the code like
public partial class HybridPanel: Panel {
[DefaultValue(BorderStyle.FixedSingle)]
public virtual new BorderStyle BorderStyle {
set {
if(value!=borderStyle) {
borderStyle=value;
base.PerformLayout();
}
}
get {
try {
return borderStyle;
}
finally {
if(borderStyle!=base.BorderStyle)
base.PerformLayout();
}
}
}
BorderStyle borderStyle=BorderStyle.FixedSingle;
bool isCollapsed, isAutoSize;
}
In this conext, the property is not only used as a variable, but also other things to do.
Access the properties in the same class is NOT considered a bad pratice, further, the complier would suggest that:
A method that is just for access a field without passing arguments, consider define as a property instead.
By the way, you might correct the description of access the member variable directory to be access the member variable directly(that is, access with the fields).
I once saw a question here about whether it is possible to embed fields in properties so they cannot be accessed in the rest of the class, e.g.
public string Name
{
private string _name;
get { return _name; }
set
{
_name = value;
// <Important stuff that would not be executed
// upon direct field access>
}
}
Sadly this is not possible, so i thought maybe it would help to set a style guideline that fields may never be accessed outside of a property. Obviously one does not want to expose every field publicly so those fields would require private properties like this:
private int _progress = 0;
private int progress
{
get { return _progress; }
set { _progress = value; }
}
If this is paired with a guideline that fields need to have an underscore as prefix one could immediately tell that something is wrong if an underscore is spotted elsewhere in the class.
So my question - or rather questions, are those:
Is this a good idea?
Does using camel-case for private properties sound reasonable?
Can anyone think of a scenario where this might prove to be problematic?
If the getter and setter have no side effects, there's no point in making a private property to wrap a private field. Either use a field and be done with it, or use an auto-property. Don't write six lines of code to express one line's worth of intent; you're just making your code harder to read.
Now, if your setter did have side effects, then that's a different matter. In that case, it's fine to have a guideline that you shouldn't set the field outside the property -- but consider that the constructor may need to set the field too. (Initially setting up the object's state may require that you bypass the side effects.) There may also be other cases where you want to use the field (deep copy, load/save, etc.) but that's why "use the property" should be a guideline, not a hard-and-fast rule: you want to give it some extra thought before you bypass the property.
As far as naming conventions, obviously it's up to you, but it looks very strange to me to have a camelCased property. In all the code I've seen, properties are PascalCased even when they're private.
I have a confusion about understanding Property and Variables
public class ABC()
{
public int A;
public int B { get; set; }
}
What is the exact difference between in A and B?
As many have pointed out, A is a field, B is a property.
The real question is, why should you care, and what to use?
I refer to a blog post of Jonathan Aneja:
(Its in VB, but it applies to C# as well ;))
So why use properties over fields, 5 reasons:
1. Fields can’t be used in Interfaces
You can’t enforce the existence of a
field in an object’s public contract
through an interface. For properties
though it works fine.
2. Validation
While your application currently may
not require any validation logic to
set a particular value, changing
business requirements may require
inserting this logic later. At that
point changing a field to a property
is a breaking change for consumers of
your API. (For example if someone was
inspecting your class via reflection).
3. Binary Serialization
Changing a field to a property is a
breaking change if you’re using binary
serialization. Incidentally, this is
one of the reasons VB10’s
auto-implemented properties have a
“bindable” backing field (i.e. you can
express the name of the backing field
in code) – that way, if you change an
auto-implemented property to an
expanded property, you can still
maintain serialization compatibility
by keeping the backing field name the
same (in C# you’re forced to change it
because it generates backing fields
with unbindable names).
4. A lot of the .NET databinding infrastructure binds to properties but not fields
I’ve heard arguments on both sides as
to whether or not that’s a good thing,
but the reality is that’s the way it
works right now. (Note from me: WPF bindings work on properties)
5. Exposing a public field is an FxCop violation
For many of the reasons listed above
:)
There might be more reasons.
I would also like to point to a blog post of Jeff Atwood and conclude with a quote from it:
The really important thing to take away here is to avoid writing code that doesn't matter. And property wrappers around public variables are the very essence of meaningless code.
A is a field, B is a property. A property is basically syntactic sugar for getters and setters. The class you have defined will be compiled into something like this:
public class ABC()
{
public int A;
private int backing_B;
public void set_B(int value)
{
backing_B = value;
}
public int get_B()
{
return backing_B;
}
}
Note that this kind of conversion is true for all C# properties -- accesses to ABC.B will be converted to method calls. Properties basically provide the illusion of a "variable" while actually just being a cleverly disguised pair of methods.
This is important, because it allows you to declare your own get and set method body, which can validate values or do other interesting things:
private int b;
public int B {
get { return b; }
set {
if (value < 0) throw new ArgumentOutOfRangeException("value");
b = value;
}
}
Note that most properties will use a field to store their value. Properties seldom exist on their own, apart from fields.
In C# any "variable" that has a getter and setter is referred to as a property. A variable has no getters and setters or so that is what the text books say.
My programming instructor made us have getters and setters for almost every variable that we created in Java. Even indexing variables he made us use a getter and setter if they were declared at the global class scope. I think this might have been overkill but it did get me to make getters and setters.
The real things about getters and setters are that they more than likely do more than just set an internal variable. Most setters are going to perform some type of data validation to make certain that data can be set to the variable. A getter might also check returning data for some criteria.
If your property is private and your setters and getters are public technically anyone could access your variable and change it as if they had public access to the actual variable. So, in reality, you should check your data to make certain that it is valid or some other data check.
private int myVariable;
public int myVariable
{
get
{
return myVariable;
}
set
{
if (value < 0)
{
throw new Exception("This is your exception some where else in code");
}
myVariable = value; //remember value is something that is
//declared automatically
}
}
public string FirstName { get; set; }
The above is a shorthand way of writing the following
private string firstName;
public string FirstName
{
get
{
//...code here
}
set
{
//...code here
}
}
A property is sort of a short getter and or setter. You can add logic to the set or get of the property or make them private which means that they are not accessible from the out side, where a variable is always accessible (if it is public).
Variable is, well, a variable.
Property is a special type of method that exposes that variable. And since it is a method, therefore, you can do some other things in it apart from just exposing the variable.
From MSDN:
The Property statement introduces the declaration of a property. A property can have a Get procedure (read only), a Set procedure (write only), or both (read-write). You can omit the Get and Set procedure when using an auto-implemented property. For more information, see Auto-Implemented Properties (Visual Basic).
You can use Property only at class level. This means the declaration context for a property must be a class, structure, module, or interface, and cannot be a source file, namespace, procedure, or block. For more information, see Declaration Contexts and Default Access Levels.
By default, properties use public access. You can adjust a property's access level with an access modifier on the Property statement, and you can optionally adjust one of its property procedures to a more restrictive access level.
There is a very good article (link below) about using fields/variables vs Properties from Microsoft itself. Though the article essentially talks about a FxCop violation rule, it clearly defines the difference between the two and the exact usage guidelines.
An excerpt from the article:
The primary use of a field should be as an implementation detail.
Fields should be private or internal and should be exposed by using
properties. Accessing a property is as easy as accessing a field, and
the code in a property's accessors can change as the type's features
expand without introducing breaking changes.
Refer:
https://learn.microsoft.com/en-us/previous-versions/dotnet/netframework-3.0/ms182141(v=vs.80)
In your example A is a public field on the class ABC and B is a public property on the class ABC. Specifically, B is an auto-implemented property. What this means is that "under the hood" the compiler does some of the work for you and effectively transforms your code into:
public class ABC()
{
private int b;
public int A;
public int B
{
get
{
return b;
}
set
{
b = value;
}
}
}
Variable is defined basically for accessing value from a class or into the same class according to their modifier assigned to those variable.
When we define a property there two methods created for single property so extra overhead is generated that is the drawback of property.
The advantages of properties is to get or set value into private variable of class.
I have classes which have automatic properties only like public customerName {get; set;}. They are public because they are accessed outside the class. They can also be accessed inside the class. They offer good encapsulation and better debugging. I can put a breakpoint on one if I need to know who is accessing it and when.
My question is what are the disadvantages of using properties only with no corresponding fields? I can make the setter or getter private, internal.. etc which means I also have flexibility of scoping it when needed.
Serialization with BinaryFormatter - you have big problems if you need to change your property to a "regular" property later, for example to add some validation / eventing /etc - sinc BinaryFormatter uses the field names. And you can't duplicate this, since the field name the compiler generates cannot be written as legal C#.
Which is a good reason to look at a contract-based serializer instead. See this blog entry for more info.
You can't create truly read only property, because you have to define both setter and getter. You can only use private setter to achieve pseudo-readonly property from outside.
Otherwise, as said above there are no other disadvantages.
There are no disadvantages for simple properties. The compiler creates the backing field for you. This blog entry explains how the compiler treats automatically implemented properties.
Not really a disadvantage, but you have to be aware of the default values of automatic properties. With "classic" properties we always used to initialize the backing fields, e.g. like this:
private bool _flag = true;
public bool Flag
{
get { return _flag; }
set { _flag = value; }
}
This made it obvious what the default value of the property is.
With automatic properties, you have to know what the default values are for the different types (e.g. false for bool). If you don't want the property to have the default value you have to initialize it in the constructor:
class MyClass
{
public bool Flag { get; set; }
public MyClass()
{
Flag = true;
}
}
This means, you have to implement a constructor if you want to initialize your properties to non default values or if a property is of a reference type (class).
But as I wrote, I do not really think of this as a disadvantage, just something you have to know.
The thing is, there is a corresponding field. You just don't see it because the compiler creates it for you. Automatic properties are just syntactic sugar or shorthand way to create the field.
No major things. Just edge cases like where you need to pass a property to a method where the parameter is passed by reference (ref or out) which isn't possible with a property (because internally, they're just get_Property/set_Property methods implemented by the compiler, not special fields of some kind) and you would need an explicit private backing field for this.
EDIT: Oh, and seconding the 'no readonly' properties, which is actually fairly common.
If you don't need to perform any specific logic in the get and/or set accessors, there's no disadvantage...
I say that they are bad from a code readability standpoint. Syntax sugar is nice for writing code but horrible for reading code. As developers the code we leave behind will ultimately be inherited by some poor developer that will have to make sense out of what we did and what is going on in the code. I really am against changing a language to simply save keystrokes when there is an established syntax for the same constructs.