In the last lesson, we covered access modifiers and made all the fields in our program private. Now we can't access these fields anymore and our program has an error when we try to run it. In this lesson, we'll cover getters and setters, which we'll use to access and change information stored in private fields. As their names imply, getters "get" information and setters "set" information.
Let's begin by adding a getter method to our Car
class for the makeModel
field:
using System;
namespace Dealership.Models {
public class Car
{
private string _makeModel;
private int _price;
private int _miles;
public Car(string makeModel, int price, int miles)
{
_makeModel = makeModel;
_price = price;
_miles = miles;
}
public string GetMakeModel()
{
return _makeModel;
}
public bool WorthBuying(int maxPrice)
{
return (_price <= maxPrice);
}
}
}
Note that we've added an _
before our private variable names and used camelCase. This is a common convention for private fields. It makes our code more readable.
We define a getter method called GetMakeModel()
. The naming convention for a getter method is Get
followed by the field name: GetNameOfProperty()
.
Getter methods are also public
. Unlike the makeModel
field itself, we want to access this method from outside the class.
The method simply returns makeModel
.
Because GetMakeModel()
is part of the Car
class, it has access to private fields inside the Car
class. That means we can call GetMakeModel()
elsewhere in our program.
We'll replace the instance of makeModel
in Program.cs
with the GetMakeModel()
method:
...
foreach(Car automobile in CarsMatchingSearch)
{
Console.WriteLine(automobile.GetMakeModel()); // <-- This line is updated!
}
...
Let's recompile and relaunch our application with dotnet run
. The program works again and our new getter method successfully accesses the private
makeModel
field.
Let's create similar getter methods for our other Car
fields:
using System;
namespace Dealership.Models {
public class Car
{
private string _makeModel;
private int _price;
private int _miles;
public Car(string makeModel, int price, int miles)
{
_makeModel = makeModel;
_price = price;
_miles = miles;
}
public string GetMakeModel()
{
return _makeModel;
}
public int GetPrice()
{
return _price;
}
public int GetMiles()
{
return _miles;
}
public bool WorthBuying(int maxPrice)
{
return (_price <= maxPrice);
}
}
}
Let's use these getter methods to display more details about our vehicles in the console. We'll update the second loop in the Main()
method within Program.cs
to look like this:
...
foreach(Car automobile in CarsMatchingSearch)
{
Console.WriteLine("----------------------");
Console.WriteLine(automobile.GetMakeModel());
Console.WriteLine(automobile.GetMiles() + " miles");
Console.WriteLine("$" + automobile.GetPrice());
}
...
The entire updated file should look like this:
using System;
using System.Collections.Generic;
using Dealership.Models;
namespace Dealership {
public class Program
{
public static void Main()
{
Car volkswagen = new Car("1974 Volkswagen Thing", 1100, 368792);
Car yugo = new Car("1980 Yugo Koral", 700, 56000);
Car ford = new Car("1988 Ford Country Squire", 1400, 239001);
Car amc = new Car("1976 AMC Pacer", 400, 198000);
List<Car> Cars = new List<Car>() { volkswagen, yugo, ford, amc };
Console.WriteLine("Enter maximum price: ");
string stringMaxPrice = Console.ReadLine();
int maxPrice = int.Parse(stringMaxPrice);
List<Car> CarsMatchingSearch = new List<Car>(0);
foreach (Car automobile in Cars)
{
if (automobile.WorthBuying(maxPrice))
{
CarsMatchingSearch.Add(automobile);
}
}
foreach(Car automobile in CarsMatchingSearch)
{
Console.WriteLine("----------------------");
Console.WriteLine(automobile.GetMakeModel());
Console.WriteLine(automobile.GetMiles() + " miles");
Console.WriteLine("$" + automobile.GetPrice());
}
}
}
}
We should now be able to successfully compile and run our code with no errors:
Enter maximum price:
1200
----------------------
1974 Volkswagen Thing
368792 miles
$1100
----------------------
1980 Yugo Koral
56000 miles
$700
----------------------
1976 AMC Pacer
198000 miles
$400
Just as getter methods "get" an object's private
field, setter methods "set" a private
field on an existing object.
If our dealership held a sale, we would need to lower the cost of each Car
. However, since our price
field is private
, we need a setter method to set it to a new, updated sale price. Let's add that method now:
using System;
namespace Dealership.Models {
public class Car
{
...
public void SetPrice(int newPrice)
{
_price = newPrice;
}
...
}
}
We set the access modifier as public
so we can access SetPrice()
from outside the Car
class.
We use void
as the return type because SetPrice()
does not return a value.
We name the method SetPrice()
. It is standard to name setter methods by prepending Set
to the name of the field.
The method takes an argument containing the new value of price
.
The line price = newPrice;
takes our private field price
and sets it to newPrice
.
Let's see this in action. We could create an entire "admin" area of our application for car dealership employees to edit Car
information as necessary. For now, we'll simply call our method to see if it's working.
...
public static void Main()
{
Car volkswagen = new Car("1974 Volkswagen Thing", 1100, 368792);
Car yugo = new Car("1980 Yugo Koral", 700, 56000);
Car ford = new Car("1988 Ford Country Squire", 1400, 239001);
Car amc = new Car("1976 AMC Pacer", 400, 198000);
List<Car> Cars = new List<Car>() { volkswagen, yugo, ford, amc };
yugo.SetPrice(300); // <-- This line is new!
Console.WriteLine("Enter maximum price: ");
...
...
When we run our program, we'll see our newly discounted Yugo Koral. Our setter method works as expected.
In this lesson, we covered using getters and setters to access information in private fields. In the next lesson, we'll discuss the benefits of keeping our fields private.
Getter: A method to allow read access to a field. Here's an example:
public string GetMakeModel()
{
return _makeModel;
}
Setter: A method to allow write access to a field. Here's an example:
public void SetPrice(int newPrice)
{
_price = newPrice;
}
Lesson 6 of 10
Last updated more than 3 months ago.