Instance Methods
One alternative to formatting the names in the WriteLine() method call within Main() is to provide a method in the Employee class that takes care of the formatting. Changing the functionality to be within the Employee class rather than a member of Program is consistent with the encapsulation of a class. Why not group the methods relating to the employee’s full name with the class that contains the data that forms the name?
Listing 5.7 demonstrates the creation of such a method.
LISTING 5.7: Accessing Fields from within the Containing Class
class Employee
{
public string FirstName;
public string LastName;
public string Salary;
public string GetName()
{
return $"{ FirstName } { LastName }";
}
}
There is nothing particularly special about this method compared to what you learned in Chapter 4, except that now the GetName() method accesses fields on the object instead of just local variables. In addition, the method declaration is not marked with static. As you will see later in this chapter, static methods cannot directly access instance fields within a class. Instead, it is necessary to obtain an instance of the class to call any instance member, whether a method or a field.
Given the addition of the GetName() method, you can update Program.Main() to use the method, as shown in Listing 5.8 and Output 5.2.
LISTING 5.8: Accessing Fields from outside the Containing Class
class Program
{
static void Main()
{
Employee employee1 = new Employee();
Employee employee2;
employee2 = new Employee();
employee1.FirstName = "Inigo";
employee1.LastName = "Montoya";
employee1.Salary = "Too Little";
IncreaseSalary(employee1);
Console.WriteLine(
$"{ employee1.GetName() }: { employee1.Salary }");
// ...
}
// ...
}
OUTPUT 5.2
Inigo Montoya: Enough to survive on