Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I'm new to C# coming from a Java background. I'm working on a take home assignment for a coding interview. I normally write my code as following(Java):

public class Test {

   //fields

   private string fieldA;
   private int fieldB;

   public Test () {
      //.....
   }

   public String getFieldA() {
      return fieldA;
   }

   //ETC.
}

The point is that I use getters/setters like above. Now, I have a coding assignment to do for a job interview, and using C# I have stumbled across automatic properties. I was initially slightly confused about it but understand what it does now and have used it.

So for fields I would write

public string fieldA {get; set;}

It feels weird declaring fields public like that and doesn't it violate some OOP encapsulation principles ?

My question is, should I just go ahead and use automatic properties to show interviewers that I know what it is? In case I want to prevent setting a field I could just use:

public string fieldA {get; private set;}

But would it appear like I don't follow encapsulation "rules", I obviously wouldn't want to risk that. I could write it out as I do in Java.

In general what is your view on using automatic properties ?

share|improve this question
4  
How exactly are you not following encapsulation rules? –  Shahar Feb 2 at 18:06

6 Answers 6

up vote 8 down vote accepted

At a first glance, these two lines may look the same:

public string A;
public string B {get; set;}

but they're not the same at all. As you'll know, if you use a public field and in the future you need to add some logic when getting or setting the value, you can't (unless you break the interface that you're providing to others). You can't, because the value isn't encapsulated.

With an automatic property, instead, you can add more logic whenever you want, without the need to change the interface that your class provides. Just replace the automatic property with a standard one. Or, vice-versa, you can replace the standard property with an automatic one. To an external user, nothing changes.

So no, you're not even remotely breaking encapsulation. You're just using an handy syntactic sugar.

share|improve this answer
    
It should also be noted that the compiler will consider these differently when reflecting the class. A will appear from the GetFields() and B will appear from GetProperties(). –  Kevin Feb 2 at 18:52
1  
I fail to understand how changing A to a getter/setter pair would ever break the interface. Client code will be the same. –  Thomas Eding Dec 1 at 20:30
    
@ThomasEding, the code may look the same, but the CLR bytecode signature won't, so if your external client isn't in the same assembly you'd have to re-compile the client. –  JasonTrue Dec 1 at 23:41

Automatic properties are an idiomatic way of doing getters/setters in C#. If you're heading off to an interview and want to show that you're fluent in C#, by all means, use automatic properties. Especially if you come from a Java background, it should be reassuring to the interviewers if they see you're already a step ahead from writing Java in Visual Studio.

However, you are right in that using public string fieldA {get; set;} blindly is a code smell. It's very tempting and convenient to define a set of properties upfront as public and never get back to review whether they actually should be part of the class interface or not. And you can actually break encapsulation (as in 'information hiding') that way.

So to summarize: do use them, but be careful not to make them into glorified public fields.

share|improve this answer
    
Poor class design is an entirely separate concern from proper encapsulation. Using public string FieldA { get; set; } is no more of a code smell than any other line of code. The purpose of automatic properties is to provide a nice, syntactically convenient way of representing getter and setter methods for properties. Using them means that you always have well-encapsulated code, which is what this question was asking. It does not mean that you have well designed code (though it's much better than using public fields). –  Stephen Feb 3 at 2:06
    
Or to phrase it another way: creating a bunch of properties with public getters and setters may be the right or the wrong approach; but if it is the right approach, then using automatic property syntax to create those getters and setters is definitely the right approach. –  Carson63000 Feb 3 at 6:32

If you can, use them. Behind the scenes the compiler does more than just making a field public. The field is still private.

The automatic property

public string MyField { get; private set; }

would be converted into something like this (the long version)

private string _myfield;

public string MyField
{
  get
  {
    return _myfield;
  }
  private set
  {
    _myfield = value;
  }
}

Internally the compiler will generate getter and setter methods like you know them from Java. So, there's no violation of any OOP principles.

share|improve this answer
1  
To be absolutely precise, it actually creates two methods, _get_myfield and _set_myfield. You can't call those methods directly in C# (you have to use the property), but you can call them in other .NET languages. –  mgw854 Feb 2 at 19:16
    
This should be the accepted answer. The accepted one vaguely touches the OP's actual question. –  Thomas Eding Dec 1 at 20:33

I know that XAML based technology (WPF, Windows Phone) won't accept public fields like

public string a;

... for data-binding in XAML.

You must instead use public properties like:

public string a { get; set; }

Even though they look like the same. So yes, it does make difference.

share|improve this answer
  • Should you use properties over exposing fields? yes!
  • Should you use automatic properties? when it is possible/convenient to do so.
share|improve this answer

I would use AutoProperties only for DTO where you just create object to transfer between boundaries and without any behaviour.

My experience with auto properties are:

  • No way to create readonly fields! -> Solved in C# vNext
  • Developers do not think about encapsulation.
    • They tend to make to much public
    • Properties force you to create to much mutable state
  • With IList/ICollection you have problems
    • No way to expose IReadOnlyList / IReadOnlyCollection

So may advice is:

  • c'tor should express your dependencies and readonly data.
  • never expose List / Collection, expose Readonly Collections
  • change data through methods
    • value objects should be changed in atomar manner
share|improve this answer
1  
eh? auto-props allow (effectively) readonly: public int Foo{get; private set;} - also, what does this add over existing answers? –  Telastyn Dec 1 at 20:26
    
No they don't! They allows you to to private set your fields at any time in your class in each method. So you have no immutability of your fields. They do not enforce you init your members at construction time! That is what: private readonly string _field; does –  crip Dec 3 at 9:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.