C# Classes Part 1


Here is an example of a program that uses a class. All that we are doing here is to set a couple of properties after creating an Employee object. There are no methods (functions) in this class.

namespace Ch04ClassEmployee
{  // Using book: C# Beginners Tutorial
    class Program
    {
        static void Main(string[] args)
        {
            Employee myEmployee = new Employee();
            myEmployee.Age = 26;
            myEmployee.Salary = 53800.00;
            Console.WriteLine($"Age is {myEmployee.Age} and salary is ${myEmployee.Salary}");
            Console.ReadKey();
        }
    }
}

The program calls the default constructor with the new keyword. Then the age is set to 26. Age is a public property in the class, just as Salary is. In the class Employee, Age has a backing variable called age. When we set Age equal to 26, the backing variable was set to 26. When we wrote the age to the console we used the public property Age which got the value of 26 from the private backing variable age. Both the age field and the Age property have a type of int.

namespace Ch04ClassEmployee
{  // File: Employee.cs
    public class Employee  {
        private int age;  // a backing field, which is 
        // a variable - usually in small case
        private double salary;

        public Employee() {
            // default constructor
        }
        public int Age
        {
            get { return age; }
            set { age = value; }
        }
        public double Salary
        {
            get { return salary; }
            set { salary = value;  }
        }
    }
}

Leave a comment

Your email address will not be published. Required fields are marked *