I am having trouble understanding the concept of getters and setters in the C# language. In languages like Objective-C, they seem an integral part of the system, but not so much in C# (as far as I can tell). I have read books and articles already, so my question is, to those of you who understand getters & setters in C#, what example would you personally use if you were teaching the concept to a complete beginner (this would include as few lines of code as possible)?
I think a bit of code will help illustrate what setters and getters are:
public class Foo
{
private string bar;
public string GetBar()
{
return bar;
}
public void SetBar(string value)
{
bar = value;
}
}
In this example we have a private member of the class that is called bar. The GetBar and SetBar methods do exactly what they are named - one retrieves the bar member, and the other sets its value.
In c# 1.1 + you have properties. The basic functionality is also the same:
public class Foo
{
private string bar;
public string Bar
{
get { return bar; }
set { bar = value; }
}
}
The private member bar is not accessible outside the class. However the public "Bar" is, and it has two accessors - get, which just as the example above "GetBar()" returns the private member, and also a set - which corresponds to the SetBar(string value) method in the forementioned example.
Starting with C# 3.0 and above the compiler became optimized to the point where such properties do not need to have the private member as their source. The compiler automatically generates a private member of that type and uses it as a source of a property.
public class Foo
{
public string Bar { get; set; }
}
what the code shows is an automatic property that has a private member generated by the compiler. You don't see the private member but it is there. This also introduced a couple of other issues - mainly with access control. In C# 1.1, and 2.0 you could omit the get or set portion of a property:
public class Foo
{
private string bar;
public string Bar
{
get{ return bar; }
}
}
Giving you the chance to restrict how other objects interact with the "Bar" property of the Foo class. Starting with C# 3.0 and above - if you chose to use automatic properties you would have to specify the access to the property as follows:
public class Foo
{
public string Bar { get; private set; }
}
What that means is that only the class itself can set Bar to some value, however anyone could read the value in Bar.