Looking for a short & simple example of getters/setters in C#

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(string value) methods do exactly what they are named – one retrieves the bar member, and the other sets its value.

In C# 1.1 and later, 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, but the public Bar is, and it has two accessors: get, which returns the private member just as the GetBar() example above, and also a set, which corresponds to the SetBar(string value) method in the aforementioned example.

Starting with C# 3.0 and above, the compiler was optimized to the point that such properties do not need to be explicitly given a 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 entirely:

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. But from C# 3.0 to before 6.0, if you chose to use automatic properties, you would have to specify the access to the property as follows to emulate that behavior:

public class Foo
{
    public string Bar { get; private set; }
}

The set accessor would still exist, but only the class itself could use it to set Bar to some value, and anyone could still get the value.

Thankfully, starting in C# 6.0, properties can be made read- or write-only again by simply omitting the property’s get or set respectively (not to be confused with the readonly keyword):

public class Foo
{
    // Read-only property
    public string Bar { get; }
    
    // Write-only property (less common)
    public string Baz { set; }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)