7

In all the examples I see, C# auto-implemented properties are made public, even in the MSDN documentation examples. Coming from a C++ background, I've always been taught that it is a good idea to make member data private, unless there is a good reason not to.

Why is the following never used (at least I've never seen it):

private Name { get; set; }

I've looked through the MSDN documentation and read several tutorials regarding auto-implemented properties but there does not seem to be any advice on their pros and cons and when they should be avoided. Do auto-implemented properties compromise program security? Are there situations where they should be avoided? In which situations are they the ideal choice?

Thanks.

InvalidBrainException
  • 2,312
  • 8
  • 32
  • 41
  • 2
    You are confusing C# properties with C# fields. – BoltClock Jul 25 '11 at 23:29
  • Java is even worse with protected keyword – Moog Jul 25 '11 at 23:33
  • -1: you're confused. Auto-implemented properties can have any accessibility, not just public. – John Saunders Jul 25 '11 at 23:36
  • @John Saunders: But in point of fact they are frequently made public, and many examples show them as such. – Daniel Pryden Jul 25 '11 at 23:38
  • 3
    @John Saunders: Well, maybe I'm reading it wrong, but my understanding of the question is that Terribad is asking **why** people use `public int Foo { get; set }` -- that is, **why** do people create public auto-implemented properties? It's true that you can create private properties, but in my experience they are quite rare. As such, I think -1 on the question is a bit harsh: I think the OP has a legitimate question. – Daniel Pryden Jul 26 '11 at 00:03
  • @Daniel Pryden: Yes, that is exactly what I'm asking. :) Why is it that every auto-implemented property example I have read is public and never private? – InvalidBrainException Jul 26 '11 at 00:48
  • 1
    @John Saunders: Obviously they can. My question is: -Why- do they always seem to be made public in examples? – InvalidBrainException Jul 26 '11 at 00:49
  • @Terribad: Examples are meant to be simple. They are not meant to be copied and pasted. – John Saunders Jul 26 '11 at 14:18

6 Answers6

8

You are correct that auto-implemented properties that simply expose a backing field are not much of a gain over a public field.

As Alan Kay said:

But most people who use setters simply use them to simulate direct assignments to interior variables, and this violates the spirit and intent of real OOP.

However, there is an advantage to an auto-implemented property over a public field, and that is that it's a non-breaking change to later revise the implementation. If you have a public field, and code outside your class manipulates that public field, you can't change it to a private field in a future version of the class, or else any other code that touches that field will have to be recompiled. By contrast, once you have a public property, you can revise the implementation of that property in a future version, and client classes can continue using it with zero changes.

So it's useful to use auto-implemented properties for properties that right now would have trivial getter and setter implementations, but that may have more complex implementations in the future.

Community
  • 1
  • 1
Daniel Pryden
  • 59,486
  • 16
  • 97
  • 135
5

Have you asked yourself why you've always been taught that it's a good idea to make members private?

It's because (among other reasons) fields are an implementation detail. The detail of "storing data in memory", and it is an unimportant detail to any object which wishes to retrieve or set the data. Another class doesn't need to care whether he can access some memory slot somewhere - he just wants an interface for which he can pass or retrieve a value - there are the getters and setters, or properties.

Having decoupled the property from the detail of "memory based storage", we're given a large number of advantages. Primarily - we can override the behaviour of getting and setting without upsetting any code which uses the property. We can also use the property as an abstraction for retrieving data over a number of different implementations. That becomes extremely useful for testing/mocking behaviour, and providing alternative storage. If other classes depend on the implementation detail of "memory storage", you are not going to be able to change the behaviour of your class without breaking all those.

Before auto properties came along, we would typically store a field and create a getter and setter to encapsulate it for the reasons described above. An auto property automates that for us. We might write code that commonly uses fields everywhere in code, but we do so holding the idea of "I'll do this as a field for now, but that may be subject to change later if the criteria change".

Since a class knows about it's own implementation, it's usually a pointless endeavour to create private auto properties, you're not hiding the detail that's already known. Protected auto properties can be useful if you need to expose to subclasses.

As for situations where they should be avoided: When you want readonly data. (data which will not change after the object is constructed). Auto-properties lack the syntax to allow you to create an automated property that's backed by readonly data.

Mark H
  • 13,797
  • 4
  • 31
  • 45
  • 1
    Thanks for the lengthy explanation. Regarding your last paragraph, I thought this was a way to create immutable auto-properties in the latest C# version: `public Name { get; private set; }` – InvalidBrainException Jul 26 '11 at 02:37
  • 2
    That only makes the property "read only" to external objects, but not to the class itself. It doesn't perform the same function as `readonly` keyword on field.s – Mark H Jul 26 '11 at 02:46
3

Auto implemented properties have a private backing member. Compiler adds them for you. Its just a shortcut for

private int _aMember;
public int AMember {
           get {return _aMember;} 
           set {_aMember = value;} 
}

You use them you have no real logic in the getter/setter (other than needing to encapsulate).

Mrchief
  • 75,126
  • 20
  • 142
  • 189
2

Auto-implemented properties are just a shortcut for a common pattern. Any time you would have a private member with corresponding get and set functions in C++, you can accomplish the same thing with an auto property in C#. They don't introduce any different best practices or security issues.

Eric Mickelsen
  • 10,309
  • 2
  • 30
  • 41
2

Auto-implemented properties with public getters and setters are shortcuts for private backing fields with trivial get and set implementations.

You should think of them as akin to private fields with public get and set methods in C++. That's a role for properties on C#.

jason
  • 236,483
  • 35
  • 423
  • 525
1

Properties aren't "member" data. They are kind of your

const T& field() const;
T& field();

type of things, or get and set methods, i.e. they are accessors.

If you don't need member exposed, don't express them in properties. In the case of autogenerated ones, you can simply (as of C# 2.0 afaik) write

int SomeProperty { get; private set; }
Grozz
  • 8,317
  • 4
  • 38
  • 53