Possible duplicate:
What is the difference between a property and a variable in C #
I started working with C # a few weeks ago, and this is what really listened to me. C # allows the use of so-called “magic” getters and setters, also known as “syntactic sugar”. So, I can do something like this:
public int myInt { get; set; }
But in terms of encapsulation, this is pointless. Firstly, the data item is publicly available , and I can get / set it using the point operator. However, if I do this:
private int myInt { get; set; }
I cannot access it at all, as myInt is inaccessible due to protection level . What is this actually doing? I thought this should be an easy way to perform data encapsulation, so I would not have to do this:
private int myInt; public void setMyInt(int i) { myInt = i; } public int getMyInt() { return myInt; }
But this is not so. As far as I can tell, I'm just making these variables publicly available. I thought maybe I could do something like
public int myInt { get; }
That way, the client could get it, but not set , but no, public access is still allowed. So what gives?
EDIT I'm not trying to do something specific, I just want to understand how it works. To clarify:
Creating a public variable does not perform encapsulation, especially when I can access it using the point operator. Writing getters and setters for the private variable allows you to make changes to the variable, but gives you more control over how this actually happens.