C# Property Example


This entry is part 10 of 11 in the series C# Classes

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.

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.

Below is our code. First we show the main program in action. The next code listing is our Person class. In the Main program the first thing we do is instantiate the Employee class to create an Employee object. Next we set the Age to 26 and the Salary to 53800. Next we write these two to the Console.

In our last code listing on this post we illustrate how we can set a default value to a property and still use auto implemented properties.

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();
        }
    }
}

Below is our class. Our backing field, age, is written in camel case. Sometimes backing fields start with an underscore. Our backing field is private. Our properties are public.

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;  }
        }
    }
}

Auto-implemented properties make for a lot less coding, particularly when you use the prop code snippet prop+Tab+Tab. The code below uses getters and setters but notice that we can initialize the backing variable that the compiler creates right in our declaration. Very cool.

public string Location { get; set; } = "C:\\Program Files";  // default
Series Navigation<< C# PropertiesC# Access Modifiers >>