Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between public {get; set} and programming getters and setters [duplicate]

Possible Duplicate:
What is Difference between Property and Variable in C#

I started working with C# a few weeks ago, and this is something that has really been bugging me. C# allows these so-called 'magic' getters and setters, also known as 'syntactical sugar'. So, I can do something like this:

public int myInt { get; set; }

But from an encapsulation standpoint, this is pointless. For one, the data member is public, and I can get/set it using the dot operator. However, if I do this:

private int myInt { get; set; }

I can't access it at all, as myInt is inaccessible due to protection level. What is this actually doing? I thought this was supposed to be an easy way to accomplish data encapsulation, so I wouldn't have to do this:

private int myInt;
public void setMyInt(int i) { myInt = i; }
public int getMyInt() { return myInt; }

But it's not. As near as I can tell, I'm just making these variables public. I thought maybe I would be able to do something like

public int myInt { get; }

So the client could get it, but not set it, but no, public access is still allowed. So what gives?

EDIT I'm not trying to do anything specific, I just want to understand how this actually works. To clarify:

Making the variable public doesn't accomplish encapsulation, especially when I can access it with the dot operator. Writing getters and setters for a private variable allows you to make changes to the variable, but gives you greater control over how that actually happens.

like image 916
Mike G Avatar asked Nov 30 '22 23:11

Mike G


2 Answers

You're trying to write

public int MyInt { get; private set; }

EDIT: The point of auto-implemented properties is not to provide additional encapsulation, but to avoid fields.
If you make a class with a public field (publit int MyInt;), and someone uses that field, you cannot change it to a property later, or you'll break any compiled assemblies that use it.

Using an auto-property gives you the same simplicity and concision as a field, but allow you to later replace it with a full-blown property (containing additional logic) without breaking anything.

like image 23
SLaks Avatar answered Dec 05 '22 09:12

SLaks


The purpose is that you maintain encapsulation through future modification.

If you initially write your class using automatic getters and setters:

public int Count { get; set; }

Then it'll maintain precisely the same external interface if you then change it to

public int Count {
    get { /* very complicated logic */ }
    set { /* even more complicated logic */ }
}

The automatic ones are just to help you with the simple properties at first.

like image 104
Matthew Walton Avatar answered Dec 05 '22 08:12

Matthew Walton