First of all, none of your code sample will compile. Let's try to reformulate the question the way it compiles:
class SomeDeclaringType {
private int myInt; // "private" could be omitted; this is the default
// what happens if you change it to "public"?
public int MyInt { // could be "internal" instead of "private"
get { return _myInt.Value; }
set { _myInt.Value = value; }
}
//...
}
First of all, you could easily find all answers here:
http://msdn.microsoft.com/en-us/library/x9fsa0sw.aspx[
title="New Window">^].
Read about the use of accessors; I don't want to repeat the documentation.
You could compare the code with the case where you change
private
to
public
(or
internal
; by the way, read about access modifiers:
http://msdn.microsoft.com/en-us/library/wxh6fsc7.aspx[
^].) What's the difference? Well, it would work the same way, only the code would be totally pointless: you would expose
myInt
to the user which would provide exact same functionality as
MyInt
. Isn't it obvious?
Moreover, you don't need to have
myInt
at all, because those trivial getter and setter can be auto-implemented:
http://msdn.microsoft.com/en-us/library/bb384054.aspx[
^].
So, this code would be 100% identical to the first code sample:
class SomeDeclaringType {
public int MyInt { get; set; }
}
Note that this property provides same exact functionality as just the public field. Why we use those trivial properties then? Well, this is mostly the element of culture, but also the maintainability of the code. First of all, using any public (or even internal) fields is considered bad style; and using properties is considered good style. Again, why?
Because the public/internal member is a part of contract. And the property allows to add functionality without changing contract. You can do it by adding a body to the setter and getter; and this body is only needed when you need to add a
side effect to the operation of reading of the property value or assigning the value to the property.
—SA