c# – Storing data inside objects (by using “fields”)

Whenever you create an object (aka an instance of a class), you often want to store data within that object. You can think of this info as the object’s metadata. For example, lets say want to have a class called “Employee”, and you want to use that class to create “employee” objects, and each employee-object needs to store the following info:

firstname
age
DateJoined
Salary

Note: the words “instance” and “object” are synonyms.

In order to make this possible, you first need to write your Employee class to accept this info. After that, you can call on the class to instantiate the object and pass the metadata into it.

There are a number of ways to write your

1st Approach: Store the data directly in an object, using “Fields”

In this approach we have declared inside the employee class, that an employee-object can store 3 bits of data:
age,
firstname,
salary.

In C#, these items are referred to as “fields”, and whenever you declare a new field, you have to also specify what type of data it can hold. For example in in case of the “age” field, we have specified that it can only hold integers (as indicated by the “int”).

We also have to specify the access level in the form of access modifiers. We will cover more about access modifiers later.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp
{

    class Employee
    {
        public int age;
        public string firstname;
        public double salary;
    }

    class Program
    {
        static void Main()
        {
            // here we create a new object using the Employee class.
            Employee Dave = new Employee();

            Dave.age = 50;
            Dave.firstname = "David";
            Dave.salary = 35461.32;
            Console.WriteLine("{0} is {1} years old and earns  £{2} per year.", Dave.firstname, Dave.age, Dave.salary);
        }
    }
}

This will output:

Here we have written a really simple “Employee” class. We then instantiated it from within the Main method, by creating an object called “Dave”. After the object has been created, we then populated it with data.

However the above approach isn’t best practice mainly because the fields’ access modifiers was set to “public”. This breaks one of the 5 pillars of OOP, called encapsulation, which requires that access to a class’s field must be restricted so that only methods within the class can get/set the field’s value.

If we simply replace “public” with “private”, then the the program will fail with the following errors:

“private” means that only methods within the class itself can read/modify (aka get/set) the field. We are allowed to make these methods public, so that we can call these methods from outside the class….which is what we do in the next approach.

2nd Approach : Access/Modify (private) fields via the use of (public) methods.

Writing the code like above isn’t best practice. That’s because a class should be encapsulated. hence a class’s internal fields should not be readable/writeable directly. In other words the fields need to be set to “private”, and we access/modify these fields using methods.

To make this possible, what we could do is write a method for setting a field’s value, and another method for getting a field’s value. That means we will end up creating 2 methods per field, and since we have 3 fields in the Employee class, it means that we will have to write (3*2) 6 methods altogether.

i.e:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Employee
{
    private int age;
    private string firstname;
    private double salary;

    public string GetFirstname()
    {
        return firstname;
    }

    public int GetAge()
    {
        return age;
    }

    public double GetSalary()
    {
        return salary;
    }

    public void SetFirstname(string ProvidedName)
    {
        firstname = ProvidedName;
    }

    public void SetAge(int ProvidedAge)
    {
        age = ProvidedAge;
    }

    public void SetSalary(double ProvidedSalary)
    {
        salary = ProvidedSalary;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Employee Dave = new Employee();

        Dave.SetAge(50);
        Dave.SetFirstname("David");
        Dave.SetSalary(35461.32);

        Console.WriteLine("{0} is {1} years old and earns  £{2} per year.", Dave.GetFirstname(), Dave.GetAge(), Dave.GetSalary());
    }
}

This again will output:

As you can see, we have added a lot more code but the output is still the same. However this second approach, while better, isn’t best practice either. That’s because:

  • A method is designed to do a lot more then setting/getting a variable info. Creating methods solely for setting/getting fields values overkill.
  • This approach has a lot more of an overhead in terms of lines of code.
  • Setting/Getting fields via methods, means that the code has become a little harder to read. For example we now have to write “Dave.age(20)” which is harder to follow. It would have been better we could just do “Dave.age=20;”

That is why there is an even better approach….which is to use “properties”. I’ll cover this in the next lesson.