Lesson Weekend

We've been using fields regularly in our C# programs but we haven't covered C# properties yet. As we've discussed, a field is a variable of any type that is declared within a class. Generally, it's a best practice for fields to be private.

On the other hand, a property is a member of a class that provides a flexible mechanism to read, write, or compute the value of a private field.

To put it more simply, a property is public and exposes a private field to other parts of the application so it can be used.

When we write getters and setters, we manually define the way our objects access their private fields. However, they're methods, not properties.

Using a Property in Our Dealership App


Let's write a property to access the _makeModel field in our dealership application.

public class Car
{
    ...
    private string _makeModel; //private field

    public string MakeModel //public property
    {
        get // a property accessor used to return the property value
        {
            return _makeModel; 
        }
        set // a property accessor used to assign a new value
        {
            _makeModel = value;
        }
    }

    ...
}

Note that we have a new public string called MakeModel. It is capitalized with PascalCase and has no underscores because it is a property. Properties have the ability to define their get and set actions. In this case, our property has get and set code that looks nearly identical to the getter and setter code we've written before.

It's worth mentioning that value within the set action is a keyword that refers to the value we want to assign to the private field. You can read more about this the value keyword on the Microsoft C# documentation.

Here's how we would call this property in our code:

car-dealership/Program.cs
...
    static void Main()
    {
        Car yugo = new Car("1980 Yugo Koral", 700, 56000);
        Console.WriteLine(yugo.MakeModel);
        yugo.MakeModel = "Worst Car Ever";
        Console.WriteLine(yugo.MakeModel);
    }
...

Run the program with $ dotnet run and this is what the output in the console should look like:

1980 Yugo Koral
Worst Car Ever

If Lonny is truly motivated to sell his cars, he might want to keep the makeModel secret. If so, we could change the get to the following:

car-dealership/Car.cs
...
    public string MakeModel
    {
        get
        {
            return "That's a big secret. You'll have to visit Lonny's to find out about our special deals!";
        } 
    ...  
...

Run $ dotnet run again, and we'll see this in the console:

That's a big secret. You'll have to visit Lonny's to find out about our special deals!
That's a big secret. You'll have to visit Lonny's to find out about our special deals!

We get the output twice, because our Main() method accesses the MakeModel property twice with Console.WriteLine(yugo.MakeModel). As this shows, properties give us tremendous control over access to private fields outside of a class.

For more examples, check out the Microsoft C# documentation on properties.

DRY It Up with Auto-Implemented Properties


We can DRY this code up and make it shorter with syntax that C# provides.

public class Car
{
    // Public auto-implemented properties
    public string MakeModel { get; set; }
    public int Price { get; set; }
    public int Miles { get; set; }

    // Constructor
    public Car(string makeModel, int price, int miles)
    {
        MakeModel = makeModel;
        Price = price;
        Miles = miles;
    }
    ...
}

We are now using auto-implemented properties. We no longer have getters or setters. Instead, we've declared all properties as public and we've added the code { get; set; } to each property.

So where are our private fields? When we use auto-implemented properties, C# generates a private anonymous backing field attached to the public property. Let's use the car dealership to explain this. When we use this code:

public string MakeModel { get; set; } // a public auto-implemented property

C# is implicitly making a public property with a private backing field:

private string _makeModel; //private field

public string MakeModel //public property
{
    get // a property accessor used to return the property value
    {
        return _makeModel; 
    }
    set // a property accessor used to assign a new value
    {
        _makeModel = value;
    }
}

With auto-implemented properties, { get; set; } represents the getter and setter actions. If we want to add more advanced functionality within get and set actions, we need to write the longhand version of a property with get and set. We also need to include a visible backing field, just like in the example above.

For more examples, visit the Microsoft documentation on auto-implemented properties.

Summary


In this lesson, we covered the difference between fields and properties. We learned how to add a getter and setter to a property and how to use auto-implemented properties that include shorthand for getters and setters. From now on, use public properties to expose private fields in your code.

Terminology


Auto-implemented property: Shorthand to expose private fields with properties.

Property: Exposes a private field for use elsewhere in an application. Here's an example:

Example


Here's how to add auto-implemented properties:

public class Car
{
  public string MakeModel { get; set; }
  public int Price { get; set; }
  public string Miles { get; set; }

  public Car(string makeModel, int price, int miles)
  {
      MakeModel = makeModel;
      Price = price;
      Miles = miles;
  }
}

Lesson 10 of 10
Last updated more than 3 months ago.