Instance Methods

One alternative to formatting the names in the WriteLine() method call within Main() is to provide a method on Employee that takes care of the formatting. Changing the functionality to be on Employee rather than on 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 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 in order 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 new 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(                                          "{0}: {1}",                                             employee1.GetName(),                                    employee1.Salary);                                  // ...   }   // ... } 

Output 5.2.

 Inigo Montoya: Enough to survive on 

Essential C# 2.0
Essential C# 2.0
ISBN: 0321150775
EAN: 2147483647
Year: 2007
Pages: 185 © 2008-2017.
If you may any questions please contact us: