10

I'm using .NET 4.5 in a VSTO addin for outlook 2013. I'm having some trouble fully grasping properties and accessors. Auto-implemented accessors which I assume are when you just write get; set; rather than get { //code }, etc. are also giving me trouble. I have a dictionary I use internally in my class. Here is my code:

private Dictionary<string, string> clientDict { get; set; }
private Dictionary<string, string> clientHistoryDict { get; set; }

then later on:

clientDict = new Dictionary<string, string>();
clientHistoryDict = new Dictionary<string, string>();

I am using the same names as the properties in the code later on, within the same class.

I never actually write:

private Dictionary<string, string> _clientDict; // etc.

to create the variables I just was using the property directly.

I tried changing my code to do this, and I had some issues and realized my understanding of properties is a bit mixed up.

Here are a few questions I need clarified that I can't seem to find the correct answer to.

First, is there any reason to use a private property? My dictionaries are never accessed outside of the class or in any derived classes so is there a reason to even use properties? I don't use any special validation or anything in the setter or anything like that.

Second, when I tried to change my code to use variables and then access them via the properties like your typical property example would, I ran into problems. I found an example where the getter was set to return _clientDict, but the setter was just set; It gave me the error: that I must give set a body because it's not abstract or partial. Why would it not auto-implement the setter for me in this instance?

Last, when I call new on the properties in the same class that it is declared in, what is the difference between doing that with a property and a normal variable of the same type? Do properties differ at all from variables in that case? Is it bad practice to use properties this way when it should be accomplished with private variables?

These may be some misguided questions but I can't find any other place that has the information to help me understand these distinctions. I've been playing around with properties to try and figure all of this out but I could use so me assistance.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
ss7
  • 2,902
  • 7
  • 41
  • 90

2 Answers2

11

First, is there any reason to use a private property?

Usually, no. Properties are great for encapsulation. One advantage (there are many more) of using a property is that it can do validations before assignment. When you have something private, you usually don't need to protect things from yourself. Also, properties have the advantage of setting different accessors (private, protected, etc), where fields do not.

Why would it not auto-implement the setter for me in this instance?

We have to understand that auto-implemented properties aren't black magic. The compiler will generate a private backing field for us, instead of providing one ourselfs. From his point of view, he sees that you have a getter that returns a private field, but the setter is automatic, thatusually would indicate some kind of logical error in your code. Why would you return one value but set a completely different one? When you create a property with a backing field, you have to provide both the getter and setters, those are the rules.

when I call new on the properties in the same class that it is declared in, what is the difference between doing that with a property and a normal variable of the same type?

Semantically, Nothing. new belongs to the type being constructed and will emit a constructor call. The difference is once the newly created object is assigned. A field will cause the compiler to emit a stfld opcode. For a property it'll emit a call to invoke the property setter. When you access a property, the compiler will end up calling get_YourPropertyName vs a ldfld on the field.

Is it bad practice to use properties this way when it should be accomplished with private variables?

I wouldn't call it bad practice, but I would find it a bit weird to have a private property.

For more insights on fields and properties, see What is the difference between a Field and a Property in C#?

Community
  • 1
  • 1
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • Huge help thanks so much, just some clarification? What do you mean by fields can't have access specifiers? Wouldn't a private member variable be an example of this? I think I'm missing what you mean by field. – ss7 May 25 '15 at 15:30
  • 2
    The argument for private properties is potential for future change. Though you have no validation logic now, you may in the future, and already having a property gives you a single place to change this logic, rather than every place assignment happens in your class, making your class invariants easier to maintain. It might not be a *great* argument, especially in all cases, but it *can* help encapsulate some types of volatility. – Preston Guillot May 25 '15 at 15:31
  • @shenk A property can do this: `public string Foo { get; protected set; }`, which means only derived types may set the value of `Foo`. A field can't do that. – Yuval Itzchakov May 25 '15 at 15:31
  • @PrestonGuillot But a private field is implementation detail, refactoring it doesn't require any knowledge from the *outside*. When you use a property, you usually want to protect yourself from future changes to your public API's. I have yet to see a private property which wasn't a mistake on the programmers end. – Yuval Itzchakov May 25 '15 at 15:33
  • That's not the only reason to use a property. Besides validation logic you can run all sorts of code in the getter or setter. For example, you might have some `OnValueChanged()` in the setter (INPC is an example of this). This cannot be done with a field. – Daniel Rose May 25 '15 at 15:51
  • @DanielRose That's why I said *one* advantage :) – Yuval Itzchakov May 25 '15 at 15:52
  • My comment was about your sentence "I have yet to see a private property which wasn't a mistake on the programmers end." Personally, I always use properties, even if it isn't strictly necessary. I find it to be more consistent, instead of checking where I need a property and where a field might do. – Daniel Rose May 25 '15 at 16:02
  • @DanielRose Well, there's always a first. – Yuval Itzchakov May 25 '15 at 16:02
  • The question about the new operator is completely wrong as well as the answer. New is not called on a property or a field. New is called on a type by using one of the types constructors and creating an instance of that type. Then, an assignment operator = is used which stores the value from right hand operand in the left hand operand while the right hand operand has to be the same type or must be implicitly convertible to the left hand operand type. This is how it works with fields, but in case of properties a setter method is called, so the code is x.prop = y; turns into x.set__prop(y); – Santhos May 25 '15 at 17:16
  • Which btw means that your call stack is 1 deeper. If the setter is not implemented, the auto implementation looks like void set__prop(value) { this.__prop = value; } It is also wise to say that setters and getters should not contain complex logic, it mostly should contain only some constrains. No exception throwing, no database calls, etc. Getters and setters should be elementary and atomic. – Santhos May 25 '15 at 17:17
3

Is there any reason to use a private property?

No - that's the whole point of auto implementation. It saves you having to write all that extra code when all you want to do is get or set what's in the private member variable. .Net handles the creation of the shadowing private member variable behind the scenes.

When I tried to change my code to use variables and then access them via the properties like your typical property example would, I ran into problems. I found an example where the getter was set to return _clientDict, but the setter was just set; It gave me the error: that I must give set a body because it's not abstract or partial. Why would it not auto-implement the setter for me in this instance?

My understanding is that it's all or nothing with auto implementation. (Open to correction there though). That said I have seen code compile with the set block simply defined as set { }. Edit: Just to clarify the set { } block won't actually set the value, it essentially swallows the call and does nothing - it will compile though.

When I call new on the properties in the same class that it is declared in, what is the difference between doing that with a property and a normal variable of the same type? Do properties differ at all from variables in that case? Is it bad practice to use properties this way when it should be accomplished with private variables?

There is no real difference as far as I am aware. The exact same thing is happening, it's just that .Net is handling the plumbing for you.

amcdermott
  • 1,565
  • 15
  • 23