0

Now that C# includes automatic properties and private set, you can emulate basic traditional accessors and modifiers without an explicit field, controlling access. You can even initialize properties now.

So excuse the stupid question but when would/should fields be preferred? Both technically - what limitations are there - and in terms of best practices and coding standards, how should a modern C# developer approach this?

One presumes MS added these features specifically to remove the need for declaring the field as well as the properties, so for simple cases is it expected that's what we do, and fields should be reserved for non-trivial cases?

Is my suggestion correct: auto-properties should be used unless there is a reason not to?

I found this question: What is the difference between a field and a property? But C# has moved a long way since 2007, so I tagged this question C# v7 in case language features mean the answer has changed.

Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
  • 1
    Auto-properties are just syntactic sugar. They add no functionality. If you don't need to access the backing field directly then there's no advantage to declaring one. – D Stanley Jan 15 '20 at 15:39
  • @DStanley Question: if you use an auto-property is there still a field you can access directly then? – Mr. Boy Jan 15 '20 at 15:44
  • @Mr.Boy, [yes](https://stackoverflow.com/q/8817070/1997232). – Sinatr Jan 15 '20 at 15:46
  • @Mr.Boy Not directly. You can get to it through reflection but you don't know the compiler-generated name. If you need to access the backing field then you should declare one. – D Stanley Jan 15 '20 at 15:46
  • @Sinatr I would argue that reflection is not accessing "directly". – D Stanley Jan 15 '20 at 15:47
  • @DStanley, sorry, I miss that word.. – Sinatr Jan 15 '20 at 15:47

0 Answers0