Search code examples
c#encapsulation

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


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.


Solution

  • 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.