Stack OverflowC# Automatic Properties - Are they safe for enterprise development?
[+19] [7] Stephen
[2011-09-02 07:42:49]
[ c# coding-style automatic-properties ]

I've got some questions regarding Automatic properties! :)

Basically, we have had a reviewed 'Coding Standards' document for the place I work and these are now banned, I've tried getting these unbanned saying that they quicker to write, easiest to maintain and make development much cleaner..

But that has been dismissed on the grounds that there are issues with automatic properties in enterprise development - they cant remember what they are but they suspect its down to performance or threading. Does anyone know if this is true? or do you know anything I could put forward for another argument :)


(35) What the...? No, it is not a problem. Banning something without giving a reason is kind of a bad practice itself. - UrbanEsc
(9) Complete nonsense. Especially when they don't know the reason themselves. However, there is one reason that might lead to at least see automatic properties as a code smell. But this only makes sense if you put up a rule that defines set{_backingField=value;} as code smell as well: - Daniel Hilgarth
(12) Not sure which is worse... no coding standards, or ridiculous ones. - Timothy Strimple
(4) @Timothy: Well, I think that is easily answered: ridiculous ones are much more harmful than no coding standards. - Daniel Hilgarth
I totally agree - Instead of automatic properties we would only be writing the usual backing field code. We all use backing fields when we need things to be abit smarter.. just as it should be! - Stephen
(5) I honestly think this calls into question the competence of people who set the coding standards. Anyone who does not know that automatic properties are syntactic sugar needs to do some research to keep up the basic level of knowledge required to be a developer. Also any coding standards document that says "you must not..." without a comprehensive "because..." is not worth the bytes it takes up on your hard drive. Imagine if FX cop warnings didn't explain themselves, a coding standards document is TO HELP skilled professionals do a better job not a set of school rules for 4 year old. - Ben Robinson
(1) you're surely trolling right? - Jon Preece
@Daniel you are absolutely right most developers will tend to follwo whatever standards seem to be in place in the existing code base out of basic common sense. - Ben Robinson
@Daniel Hilgarth i disagree with the author of the article you posted - a lot. But too much for the comments so i will leave it at that. - UrbanEsc
@Stephen: Just a thought: I refuse to follow rules that are nonsense in my eyes and for which no reasoning exists. I openly tell this the manager that put up the rule. Normally, this leads to one of the following: (1) the rule is removed (2) a good discussion ensues and the rule is fixed - Daniel Hilgarth
@UrbanEsc: I would love to here your thoughts - maybe you can post them as a comment to the article? - Daniel Hilgarth
(1) @Daniel, so you are never wrong then ;-) - Ben Robinson
@UrbanEsc I agree, first thing that came to mind was that there are perfectly valid reasons to set a property to null, e.g. An ORM mapped entity where you want to null out a mapped DB field. - Ben Robinson
@Ben: Right you are ;-) Actually, whenever I refused to follow a rule, there indeed was a problem with it, even if it just was the missing reasoning. In such cases and if the rule itself really made sense, the fixed rule was the same as before, just with an added reason as to why the rule exists. - Daniel Hilgarth
@Ben: The author sees an ORM mapper as an application boundary for which this rule - and others he put forth - don't count:… - Daniel Hilgarth
@Daniel in short i dont like how this article tries to emphasize the enforcement of business rules via property setters. eg The example with temperatures: why is it not valid to set 100? Is that always wrong? Even if its true? Like, i'd like to work with the temperature of the sun. I can't, i get an exception from the class that thinks i am wrong. Business rules should be applied declaratively and not superimposed by a class developer who thinks he is particularly more clever than the user (when in fact, he cant be) - UrbanEsc
@UrbanEsc: If you don't enforce the business rules in the business objects, where would you enforce them? Furthermore, the sample with the temperature actually was about -100 which should be invalid if the unit was Kelvin, because -100K simply doesn't exist as 0K is the coldest possible temperature in this universe. - Daniel Hilgarth
@Daniel of course it should be implemented on business objects but there are other ways to achieve this, which are better than writing your rules into property setters. Code contracts, AOP, validation rules, what have you, there are a lot of ways. Yes, they might end up generating code into your setter, but at least its not manual created code that can fail, be wrong or might need to be changed in multiple places and therefore lead to errors. At least, that is my way of thinking. Maybe i misinterpreted the article. - UrbanEsc
@UrbanEsc: Basically, you do agree with the reasons why the author doesn't like automatic properties: If you use automatic properties, you normally allow the user to assign any value to the property. If you can prevent this with other means, that's fine. It's just important THAT you prevent the user from assigning an invalid value to the property. - Daniel Hilgarth
@Daniel Just to be clear, i am not talking about his simple examples there, of course you might want to check your RetryCount on validity right there, because you could say that -1 is always wrong, and is not dependend on a domain. But more often you have to work with real domain rules. Therefore calling AutoProps a code smell is a far cry. - UrbanEsc
@UrbanEsc: A code smell is something that can be correct. It just should make you think twice. However, I don't really understand where you put your "real" domain rules if not in the property setter. - Daniel Hilgarth
@Daniel With "real" domain rules i am refering to rules which depend on the domain. "RetryCount" could be a business rule, like how often would you like to retry doing the money transfer (nah, not good, but whatever). "RetryCount" could refer to how often you would like to try to reconnect to a database, and would therefore not be a business rule. At least not how i understand that term. - UrbanEsc
@Daniel having read the article I agree with some of the points but i think none of them have anything to do with automatic properties, e.g. the temperature one was basically an int is not a good type for a temperature property, which is pretty obvious, even if you discount the UOM and range validation how would you record a temperature of 27.43 units. - Ben Robinson
[+28] [2011-09-02 07:45:53] Adam Houldsworth [ACCEPTED]

Absolute nonsense, it's just syntactic sugar and will compile into the same thing eventually if they think the "right" way is manual backing fields...

Performance and threading issues do not stem from auto-properties, properties or any other construct in C# programming. They stem from the minds of the people designing the system and likely the same people enforcing this ban...

An argument would be to produce proof of said issues, if no proof materialises then your argument to continue using them stands. You could also go down the "reduced productivity" route.

I'm guessing someone doesn't like the way they look in the code, and unfortunately has the power to stop them being used.

As for them being safe in enterprise-scale applications: I have worked on a few and have never seen a defect come through that was caused by the use of a stock auto-property or stock property. Plenty from abusing properties, but nothing from the most basic usage.

Your last guess is also mine. Usually that would be someone coming from a different dev background, who tends to dislike C# (and other languages in general) features. - UrbanEsc
@UrbanEsc yeah it's a shame really. I think an important mindset is to enjoy the technology you use, even if it isn't part of your grass-roots. If they aren't enjoying the technology, they shouldn't be bothering. - Adam Houldsworth
The only issue I've ever seen with the use of Automatic Properties is when the object is serialized across the wire using the XML Serializer (like what CSLA uses by default in it's WCF Data Portal). It will throw and catch XmlParseExceptions because the backing field gets a name like <>__PropertyName and that's what gets used as an XML tag. Unless you run your debugging sessions where you catch exceptions as soon as they're thrown (rather than if they're unhandled) you'll likely never have an issue with them. - Agent_9191
@Agent_9191 didn't realise the backing field was used, I thought by default the XML serializer took the public member name, the backing field will be private? - Adam Houldsworth
Correct. Because serialization will serialize everything about the class, the fields go along with. - Agent_9191
@Agent_9191 my understanding is that default XML serialization provided by .NET only serializes the public members, so fields are usually left alone (2nd paragraph): - Adam Houldsworth
(1) What Agent_9191 is talking about is actually a fairly well documented "bug". The issue comes from the fact that the Serializer was built to work with .NET 2 (and actually before that as well), while Automatic Properties were not added till 3.5. So the rule of thumb is if you use Auto Properties, you should use the newer DataContract classes that support Auto Properties. Of course, some frameworks (like CSLA) were never updated to do that. - Timothy Baldridge
@Timothy do you have any links to this? Does this mean that the compiler creates a public backing field for auto-implemented properties? - Adam Houldsworth
@Timothy I can't find anything about this, and I just rigged up a simple console app to try serializing auto-properties and it works as expected. - Adam Houldsworth
This is using the json serializer, but the same concept applies:… For your example, go to Debug->Exceptions and tell the debugger to always break on an XmlException. Or also look at the "output" window while the app is running. The exception is thrown and caught from within .NET, so it never bubbles up to your app, but this will no doubt have a slight performance impact. - Timothy Baldridge
@Timothy ok so this isn't using the XmlSerializer type? I had no exceptions and a nicely formatted XML document with my auto-properties in it. However, this makes sense to me as the backing fields should be private. Serializers that access the private fields, as you say, may have problems if they don't like the naming. - Adam Houldsworth
The link above is showing how private backing fields are implemented with Auto Properties. As @agent_9191 mentioned, Foo gets formatted as <>__Foo. So in the xml serializer, it will try to do this <MyObj <>__Foo="Bar"/> . <> is illegal as a XML attribute name, hence the exception. - Timothy Baldridge
@Timothy let us continue this discussion in chat - Adam Houldsworth
[+18] [2011-09-02 07:46:54] CodeCaster

You could compare the resulting MSIL (which is obtainable through ildasm.exe [1]), which will show that auto-implemented properties compile to almost the same bytecode as manually created properties.

The following code:

class AutoProperties
    public String AutoName { get; set; }

    private String _manualName;
    public String ManualName
        get { return _manualName; }
        set { _manualName = value; }

Will create (almost) the same variables and methods in MSIL:

<AutoName>k__BackingField: private string
_manualName : private string
get_AutoName : string()
get_ManualName : string()
set_AutoName  : void(string)
set_ManualName  : void(string)
AutoName : instace string()
ManualName : instace string()

Thank you for that code sample, that was very useful. - Stephen
[+5] [2011-09-02 07:55:05] Henrik

They are safe, but can be abused. For a readonly property that is only set once in the constructor, I prefer a property with a readonly backing field over public SomeType MyPrperty { get; private set}.

But of course, that's no reason to completely ban automatic properties.

Of course it would be quite easy to have that specific requirement in the coding standards. - Ben Robinson
[+3] [2011-09-02 14:49:20] Darryl Braaten

The only reason to avoid autoproperties is if you are using [Serializable] objects as attributes for serialization can only be added to fields and not properties. This is important if you want to allow different versions of objects to be used by different code versions.

Thank you for that, Our software is in fact client and server and we use the Serializable attribute on most of our classes, Is there a way to get these working using remoting and serializable attributes? - Stephen
They will work with serialization, but you can't add attributes to the fields that underlay the autoproperties. What this means is if you are trying to version your classes so the serialization works up version and down version you can't mark the fields with the correct attributes to make this function. - Darryl Braaten
[+1] [2011-09-02 07:46:58] TeaWolf

Automatic properties are just syntactic sugar. In the background, the compiler will create regular backing fields for you (can easily be verified with .NET Reflector or any other IL disassembler).

[+1] [2011-09-02 07:47:02] Jakub Konecki

I cannot think about any possible issue with automatic properties. When you inspect the generated IL you will notice that all the compiler does is to generate a backing field and get and set methods.

There is no danger in it.

[+1] [2011-09-02 07:47:15] ColinE

Automatic properties are totally safe for enterprise (or casual software develoment). They are expanded by the compiler to a property with a getter and setter backed by a field, hence the perform in exactly the same way as the more manual / verbose property.