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?!
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?!
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.
I'd like to see
public int MyInt{ get; private set; } more, ;)
but @BFree nailed it
Do you like someone you don't know messing with your private parts? I hope not. This is a way to provide what is essentially a proxy for something you own but don't want to cede control over. If you decide you want to validate that int's are positive, you can start doing that if you code as shown.
C# makes this transparent now with automatic properties.
That's the old way to do it. The way you prefer ("automatic properties") it a relatively new construct in the language. A few years ago, we always had to use private variables.
There may be other reasons to use private variables as well, though not in the simple example you provide. If, for example, you needed to intialize the property with a default value, you can't really do that cleanly with automatic properties; instead you need to initialize in the constructors.
public int MyInt{ get; set; } was a feature added in C# 3.0 called Automatic Properties. C# 2.0 does not support this and requires the private variable with the explicit getters and setters. Therefore, a lot of older code or backwards compatible code will use the explicit getters and setters.