Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you use private variables with C# getter/setters?

Tags:

c#

I see this all the time:

    private int _myint;

    public int MyInt
    {
        get
        {
            return _myint;
        }
        set
        {
            _myint = value;
        }
    }

To me this seems identical to:

    public int MyInt{ get; set; }

So why does everyone do the former... WHY THE PRIVATE VAR AT ALL?!

like image 401
y2k Avatar asked Feb 12 '10 19:02

y2k


3 Answers

An example to expand on what @BFree is saying:

private int _Whatever; 
public int Whatever
{
    get {return _Whatever;}
    set 
    {
        if(value != _Whatever)
        {  
          // It changed do something here...
          // maybe fire an event... whatever

        } 

        _Whatever = value;

    }
}
like image 172
AGoodDisplayName Avatar answered Oct 28 '22 05:10

AGoodDisplayName


First of all, this is new to C# 3.0, it wasn't around before that. Second, if you want to add any custom logic to your getter and setters, you have no choice. So yes, in your example where there's no custom logic, it's the same thing (in fact the compiler generates that for you behind the scenes) but if you want to raise an event for example, or anything like that, you have to be explicit about it.

like image 20
BFree Avatar answered Oct 28 '22 03:10

BFree


I'd like to see

public int MyInt{ get; private set; }

more, ;)

but @BFree nailed it

like image 27
hunter Avatar answered Oct 28 '22 04:10

hunter