Why should I use an automatically implemented property instead of a field? - c#

Between these two:
With Property:
class WithProperty
{
public string MyString {get; set;}
}
With Field:
class WithField
{
public string MyString;
}
Apparently I'm supposed to pick the first one. Why?
I've heard the argument that the point here is to allow interface changes, but
if I have the second one, and change it to the first one, no other code should
ever have to change. When recompiled everything's just going to point to the
property instead.
Am I missing something important here?

The most important difference is the fact, that if you use a field, and later need to change it to a property (say, to enforce some validation), then all libraries calling your code will need to be recompiled. It's true that you can compile the exact same code if the name stays the same - but the consumers of your code will still need to be recompiled. This is because the IL generated to get the value is different between a field and a property. If it already is a property, you can make a change without forcing consumers of your code to change.
This may or may not be an issue for you. But the property is almost the same amount of code, and is considered best practice. I would always go for the property.

The property can be changed later if you need to add validation or other logic without breaking other assemblies.
Also, the property can be used with databinding.

The important part you are missing is the gravity of this statement:
When recompiled
When your code point to a field and you change it to point to a property of the same name, the C# itself doesn't change, but the resulting IL does - it generates a method call to the getter or setter as appropriate.
Not every app has all of it's pieces contained in a single distributed unit. Many apps rely on interfaces for pluggability/expandability. If you have an app with an interface to a field and you want to change it to a property to take advantage of the power of properties, the app has to be recompiled and redistributed. You might as well just make it a property in the first place.

With a property, you can easily extend it to include new logic.
For example, if you need to add validation logic to the set.

This article goes into several additional reasons why you should prefer properties:
http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx

Related

Is is a good practice to store propery names in a public constant string?

In order to protect ourself from failure because of any renaming of properties (Let's say you regenerate your poco classes because you have changed some column names in the relevant Db table) is it a good practice to decalre constant strings that keep the property names inside?
public const string StudentCountPropertyName = "StudentCount";
public int StudentCount {get;set;}
For example: Think about a DataBinding; where you type the property name in the DataFieldName attribute explicitly.
Or this is not a good idea and there is a better and still safer way?
It is always a good idea IMHO to move any 'magic strings' to constants.
You could consider using lambda expressions to 'pick' your properties, for example:
GetDataFieldName(studentCollection => studentCollection.Count)
You will have to implement GetDataFieldName yourself, using a bit of reflection. You can look at HtmlHelperExtensions from MVC to see how it can be done. This will be the most safe approach, which gives you compile-time errors when something goes wrong and allows easy property renaming using existing refactoring tools.
From one point of view: if you using this property name multiple times it is good practice. It will help for sure with the refactoring and when you for example change property name you see that you need change this const also.
From another point of view i guess it will be ugly when my class with 10 properties will have 10 additional consts. Another solution if you want avoid consts or explicit name typing can be getting property names through the reflection.
Use such approach or not you should decide yourself.
I think it's a common practice to put this "magical string" or "magical numbers" in some kind of strong typed store.
Something you can consider is to code it in a Aspect Orientied Way.
For example the calls to notifypropertychagned can be realized with an attribute implemented with an aop framework, like PostSharp .
[NotifyChange]
public int Value {get;private set}
This tools also have some downsides but i think there are scenarios where they can save you a lot of work
I do not know if I fully understand your question, but if I understand it right I would have used an attribute for that, an example could be the use of ColumnAttribute in Linq which you use to map a property to a specific column in a database (http://msdn.microsoft.com/en-us/library/system.data.linq.mapping.columnattribute.dbtype.aspx), like in this example:
[Column(Storage="ProductID", DbType="VarChar(150)", CanBeNull=False)]
public string Id { get; set; }
And I would never use DataFieldName, I would DataBind to the strongly typed objects (and of course also make an interface to the class that uses the property above so I easily can change the implementation in the future ;))
I suppose if the names are used in many places then it would be easier just to change them in this one place and use the constant as described in your comment.
However, a change to a database column name and object property name implies a change to your conceptual data model. How often do you think this is going to happen? In the early stages of a project, whilst conceptual modelling and implementation are paralellised across a dev team, this may be quite fluid, but once the initial conceptual modelling is done (whether this in a formalised conscious manner or just organically), it's usually quite unlikely that fundamental things like these are going to change. For this reason I think it's relatively unusual to have do this and the technique will only be productive in edge cases.
Absolutely. It's a good idea.
By the way, I would argue that these kind of things could be better stored in application settings, because you can define such things in an application configuration file later by overriding these settings.
Doing that this way you'll avoid re-compiling if some database, POCO or whatever changes, and as in newer Visual Studio versions like 2010, you can tell it to generate settings with "public" accessibility, you can share strongly-typed settings with any assembly that reference the one containing them.
At the end of the day, I'd change your code with DataBindingSettings.StudentCountPropertyName instead of a constant.
Easy to manage, more re-usable, and readable, as "you configure a data-binding with its settings".
Check this MSDN article to learn more about application settings:
http://msdn.microsoft.com/en-us/library/a65txexh(v=VS.100).aspx

How would one write an Attribute that would set the default value of an auto-property

I've read the post for setting default properties via an attribute, which end with DefaultValue is for Design Mode or Serialization.
BUT, is there a way to write an Attribute that will do what these posts require: default the property to some value.
If there is a way -- how would one start writing such an attribute?
Thanks,
L-
You can't, basically.
You can set the default in the constructor, though.
As it happens I did implement something that did this very recently, but that was using factory-based construction; the factory checked for [DefaultValue] and set the value via reflection. But attributes can't cause arbitrary code execution unless you use a re-writer like PostSharp.
If the constructor is too far away for your liking, you will have to use a field-initializer and write the get/set against the field.
Unfortunately attributes are just metadata, meaning they cannot run or do something on their own.
However nothing prevents you from writing an extension method with a name like SetDefaultValues that reads default values from attributes and assigns them to properties.
I've done a similar thing in a recent project, and it proved to be a good decision because it kept all default values defined in a declarative style in a single place.
There is an interesting article on CodeProject peering into different strategies for implementation of [DefaultValue]-based initialization and comparing their performance. I suggest you check it out.

DesignOnly attribute does not hide a property in runtime

I'm building a custom web control with a public property which I only want to be available in design time (i.e. make it unavailable in code behind).
The DesignOnly attribute promises to do just that, but when I set [DesignOnly(true)] it has no noticeable effect whatsoever:
[Bindable(true)]
[Category("Appearance")]
[DefaultValue(null)]
[Localizable(false)]
[DesignOnly(true)]
public string MyProp
{
get
{
return ViewState["MyProp"] as string;
}
set
{
ViewState["MyProp"] = value;
}
}
The property still appears in code behind IntelliSense. Setting a value to it in code behind works. In these respects, the behavior is just as if the attribute had never been set. And I've cleaned and rebuilt the complete solution. Twice.
Am I doing it wrong? Can you please tell me what is the right way to go about this, then?
Many thanks in advance.
The DesignOnly attribute promises to do just that
Actually, no; it tries to make it clear when accessing it in code isn't available; if you lie (i.e. claim that something is design-only when it is available) then you should expect it to misbehave. The compiler knows what is available, and this design-only attribute is not defined in the C# spec, so it makes no difference to the compiler if you add this attribute.
Try adding:
[EditorBrowsable(EditorBrowsableState.Never)]
which the code editor (IDE) looks at (but only when using a separate assembly) - note that this doesn't stop you using it - it just hides it.
I believe the MSDN text is trying to describe the difference between properties that actually exist on code, vs properties that only pretend to exist; you can actually do all sorts of things to make fake properties appear in the designer, and it is these pretend properties that might be marked as design-only.

C# read-only calculated properties, should they be methods?

I have several entities that have calculated fields on them such as TotalCost. Right now I have them all as properties but I'm wondering if they should actually be methods. Is there a C# standard for this?
public class WorkOrder
{
public int LaborHours { get; set; }
public decimal LaborRate { get; set; }
// Should this be LaborCost()?
public decimal LaborCost
{
get
{
return LaborHours * LaborRate;
}
}
}
It's OK to use calculated properties rather than methods, as long as the calculation doesn't take a noticeable time
See Property usage guidelines
I think methods should perform actions on the object, typically change the state of the object. Properties should reflect the current state of the object even if the property is calculated. So you should keep your properties IMO.
I think they should all be properties. As long as it doesn't change the state of the object, I'm cool with it as a property.
Additionally, if I'm using your class for data binding (WPF, etc.), then I can bind directly to your property without having to modify/extend the class.
If they are a) lightweight and b) have no side effects, I would make them Properties.
Lightweight is a bit fuzzy of course, but the rule of thumb is: If I ever have to worry calling a Property (be it in a loop or anywhere else), it should possibly be a method.
I would leave them as properties. But there's not "standard" reason to do things one way or another. If you're by yourself, do whatever you like best. If you're on a team, then follow conventions the rest of your team are following.
If a property is particularly expensive to calculate, I might change it to a GetWhatever() method. This serves as a hint to whoever uses my class that this value requires some significant work to arrive at, and the caller should cache the value rather than calling the method multiple times.
Trivial calculations are perfectly appropriate inside of properties.
In my opinion, it's a preference; it's what you want to do. I do propreties in most cases, unless there is logic involved. Additionally, if you need to pass in parameters to change the functionality then obviously a method would apply...
Depends, if your "properties" become mammoths and require a whole slew of business logic they shouldn't be properties, there should be a method.
The example you posted looks ok to be a property. No standard way of doing it, go with your gut instinct; if it looks like it needs to do a lot you probably need a method.
It's largely just syntactic sugar anyway, so do want you is convention in your team, or what you prefer, as long as it is just returning information about the object and not changing it or interacting with other objects.
MSDN gives information about this here
Class library designers often must
decide between implementing a class
member as a property or a method. In
general, methods represent actions and
properties represent data.
Which one do you think it is? An action calculate/getLaborCost or data?
WorkOrder workOrder = new WorkOrder();
workOrder.LaborHours = 8;
workOrder.LaborRate = 20;
decimal cost = workOrder.LaborCost; // This is OK here
but if you are going to do this for the same object also:
worOrder.LaborHours = 18;
decimal newCost = workOrder.LaborCost
Now this cannot be a property. It would be a lot better to be a method.
Sometimes, you have to consider also what you're modeling... On some domains, the calculated values are often or expected to be an attribute of the model -- a Property. If this were the case, then write it as a Property even though the calculation is not at all trivial or a little bit expensive to compute. Just document it on your API or implement some caching mechanism to minimize recomputation for this property.

Properties vs Methods

Quick question: When do you decide to use properties (in C#) and when do you decide to use methods?
We are busy having this debate and have found some areas where it is debatable whether we should use a property or a method. One example is this:
public void SetLabel(string text)
{
Label.Text = text;
}
In the example, Label is a control on a ASPX page. Is there a principle that can govern the decision (in this case) whether to make this a method or a property.
I'll accept the answer that is most general and comprehensive, but that also touches on the example that I have given.
From the Choosing Between Properties and Methods section of Design Guidelines for Developing Class Libraries:
In general, methods represent actions and properties represent data. Properties are meant to be used like fields, meaning that properties should not be computationally complex or produce side effects. When it does not violate the following guidelines, consider using a property, rather than a method, because less experienced developers find properties easier to use.
Yes, if all you're doing is getting and setting, use a property.
If you're doing something complex that may affect several data members, a method is more appropriate. Or if your getter takes parameters or your setter takes more than a value parameter.
In the middle is a grey area where the line can be a little blurred. There is no hard and fast rule and different people will sometimes disagree whether something should be a property or a method. The important thing is just to be (relatively) consistent with how you do it (or how your team does it).
They are largely interchangeable but a property signals to the user that the implementation is relatively "simple". Oh and the syntax is a little cleaner.
Generally speaking, my philosophy is that if you start writing a method name that begins with get or set and takes zero or one parameter (respectively) then it's a prime candidate for a property.
Searching through MSDN, I found a reference on Properties vs Methods that provides some great guidelines for creating methods:
The operation is a conversion, such as Object.ToString.
The operation is expensive enough that you want to communicate to the
user that they should consider caching
the result.
Obtaining a property value using the get accessor would have an observable
side effect.
Calling the member twice in succession produces different results.
The order of execution is important. Note that a type's properties should
be able to be set and retrieved in any
order.
The member is static but returns a value that can be changed.
The member returns an array. Properties that return arrays can be
very misleading. Usually it is
necessary to return a copy of the
internal array so that the user cannot
change internal state. This, coupled
with the fact that a user can easily
assume it is an indexed property,
leads to inefficient code.
If you're setting an actual property of your object then you use a property.
If you're performing a task / functionality then you use a method.
In your example, it is a definite property being set.
If however, your functionality was to AppendToLabel then you would use a method.
Properties are a way to inject or retrieve data from an object. They create an abstraction over variables or data within a class. They are analogous to getters and setters in Java.
Methods encapsulate an operation.
In general I use properties to expose single bits of data, or small calculations on a class, like sales tax. Which is derived from the number of items and their cost in a shopping cart.
I use methods when I create an operation, like retrieving data from the database. Any operation that has moving parts, is a candidate for a method.
In your code example I would wrap it in a property if I need to access it outside it's containing class:
public Label Title
{
get{ return titleLabel;}
set{ titleLabel = value;}
}
Setting the text:
Title.Text = "Properties vs Methods";
If I was only setting the Text property of the Label this is how I would do it:
public string Title
{
get{ return titleLabel.Text;}
set{ titleLabel.Text = value;}
}
Setting the text:
Title = "Properties vs Methods";
Symantically properties are attributes of your objects.
Methods are behaviors of your object.
Label is an attribute and it makes more sense to make it a property.
In terms of Object Oriented Programming you should have a clear understanding of what is part of behavior and what is merely an attribute.
Car { Color, Model, Brand }
A car has Color, Model and Brand attributes therefore it does not make sense to have a method SetColor or SetModel because symantically we do not ask Car to set its own color.
So if you map the property/method case to the real life object or look at it from symantic view point, your confusion will really go away.
You need only look at the very name... "Property". What does it mean? The dictionary defines it in many ways, but in this case "an essential or distinctive attribute or quality of a thing" fits best.
Think about the purpose of the action. Are you, in fact, altering or retrieving "an essential or distinctive attribute"? In your example, you are using a function to set a property of a textbox. That seems kind of silly, does it not?
Properties really are functions. They all compile down to getXXX() and setXXX(). It just hides them in syntactic sugar, but it's sugar that provides a semantic meaning to the process.
Think about properties like attributes. A car has many attributes. Color, MPG, Model, etc.. Not all properties are setable, some are calculatable.
Meanwhile, a Method is an action. GetColor should be a property. GetFile() should be a function. Another rule of thumb is, if it doesn't change the state of the object, then it should be a function. For example, CalculatePiToNthDigit(n) should be a function, because it's not actually changing the state of the Math object it's attached to.
This is maybe rambling a bit, but it really boils down to deciding what your objects are, and what they represent. If you can't figure out if it should be a property or function, maybe it doesn't matter which.
Properties should only be simple set and get one liners. Anything more and it should really be moved to a method. Complex code should always be in methods.
I only use properties for variable access, i.e. getting and setting individual variables, or getting and setting data in controls. As soon as any kind of data manipulation is needed/performed, I use methods.
As a matter of design Properties represent Data or Attributes of class object, While methods are actions or behaviors of class object.
In .Net, world there are other implications of using Properties:
Properties are used in Databinding, while get_ / set_ methods are not.
XML serialization user properties as natural mechanism of serilization.
Properties are accessed by PropertyGrid control and intern ICustomTypeDescriptor, which can be used effectively if you are writing a custom library.
Properties are controlled by Attributes, one can use it wisely to design Aspect Oriented softwares.
Misconceptions (IMHO) about Properties' usage:
Used to expose small calculations: ControlDesigner.SelectionRules's get block runs into 72 lines!!
Used to expose internal Data structures: Even if a property does not map to an internal data member, one can use it as property, if its an attribute of your class. Viceversa, even if its an attribute of your class properties are not advisable, to return array like data members (instead methods are used to return deep copy of members.)
In the example here it could have been written, with more business meaning as:
public String Title
{
set { Label.Text = text; }
}
Also big plus for Properties is that value of property can be seen in Visual Studio during debugging.
I prefer to use properties for add/set methods with 1 parameter. If parameters are more, use methods.
Properties are really nice because they are accessible in the visual designer of visual studio, provided they have access.
They use be used were you are merely setting and getting and perhaps some validation that does not access a significant amount of code. Be careful because creating complex objects during validation is not simple.
Anything else methods are the preferred way.
It's not just about semantics. Using properties inappropriate start having weirdness occur in the visual studio visual designer.
For instance I was getting a configuration value within a property of a class. The configuration class actually opens a file and runs an sql query to get the value of that configuration. This caused problems in my application where the configuration file would get opened and locked by visual studio itself rather than my application because was not only reading but writing the configuration value (via the setter method). To fix this I just had to change it to a method.
Here is a good set of guidelines for when to use properties vs methods from Bill Wagner
Use a Property when all these are true:
The getters should be simple and thus unlikely to throw exceptions. Note that this implies no network (or database) access. Either might fail, and therefore would throw an exception.
They should not have dependencies on each other. Note that this would include setting one property and having it affect another. (For example, setting the FirstName property would affect a read-only FullName property that composed the first name + last name properties implies such a dependency )
They should be settable in any order
The getter does not have an observable side effect Note this guideline doesn't preclude some forms of lazy evaluation in a property.
The method must always return immediately. (Note that this precludes a property that makes a database access call, web service call, or other similar operation).
Use a method if the member returns an array.
Repeated calls to the getter (without intervening code) should return the same value.
Repeated calls to the setter (with the same value) should yield no difference from a single call.
The get should not return a reference to internal data structures (See item 23). A method could return a deep copy, and could avoid this issue.
*Taken from my answer to a duplicate question.
This is simple.
1: use property when you want your data should be validated before storing in field. So in this way property provides encapsulation for your fields. Because if you leave your fields public end user may assign any value which may or may not be valid as per your business requirement like age should be greater than 18. So before value is store corresponding field we need to check its validity. In this way properties represent data.
2: Use method when you want perform some action like you are supplying some data as parameter and your method is doing some processing on the basis of supplied values and returning processed value as output. Or you want to change value of some field by this calculation. "In this way method represents action".
I come from java an i used get.. set.. method for a while.
When i write code, i don't ask to my self: "accessing this data is simple or require a heavy process?" because things can change (today retrive this property is simple, tomonrow can require some or heavy process).
Today i have a method SetAge(int age) tomonrow i will have also method SetAge(date birthdate) that calculate the age using the birthdate.
I was very disappointed that the compiler transform property in get and set but don't consider my Get... and Set.. methods as the same.

Categories