C# Automatic Properties – Should They Be Used?

ccode-reviewsencapsulationobject-oriented

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 ?

Best Answer

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.