How to define and use properties in Visual C# (308229)



The information in this article applies to:

  • Microsoft Visual C# 2005
  • Microsoft Visual C# .NET (2002)

This article was previously published under Q308229

SUMMARY

This step-by-step article shows you how to define and use properties in a Visual C# .NET or Visual C# 2005 application.

One important aim of many object oriented programming languages is to allow you to encapsulate internal details in a class. Visual C# .NET or Visual C# 2005 allows you to define properties to provide controlled access to internal details in a class.

A property can be read-only, write-only, or read-write. A get accessor provides read access, and a set accessor provides write access. You add code to these accessors to provide the appropriate functionality to get or set the property.

In this article, you create a class called Employee and define a read-write property for the employee's name. You also define a property to read the employee's salary and define a property to calculate how long the employee has worked for the company. You then create an Employee object in your application, and use its properties.

back to the top

Requirements

The following items describe the recommended hardware, software, network infrastructure, skills and knowledge, and service packs that you need:
  • Visual C# .NET syntax or Visual C# 2005 syntax
  • Object oriented concepts
  • Familiarity with Visual Studio .NET or Visual Studio 2005
back to the top

Create an Application that Contains a C# Class

  1. Start Visual Studio .NET or Visual Studio 2005, and create a new C# Console Application project named EmployeeProperties.
  2. In Class View, right-click the EmployeeProperties project, click Add, and then click Add Class.

    Note In Visual C# 2005, Add Class is changed to Class.
  3. In the C# Add Class Wizard, set the Class name to Employee and click Open.
  4. Display the code for the new class in the Code View window.
back to the top

Define Fields, Constructors, and Methods

  1. In Class View, expand the EmployeeProperties project and expand the EmployeeProperties namespace. Right-click the Employee class, click Add, and then click Add Field.
  2. Set the Field access to private, the Field type to string, and type name for the Field name. Click Finish. This adds the following field to the class:
    private string name;
  3. Repeat steps 1 and 2 (or type the code manually) to add another two fields, as follows:
    private decimal salary;
    private DateTime hireDate;
  4. Modify the constructor for the class to initialize the fields in the Employee class, as follows:
    public Employee(string name, decimal salary, DateTime hireDate)
    {
       this.name = name;
       this.salary = salary;
       this.hireDate = hireDate;
    
    }
  5. In Class View, right-click the Employee class, click Add, and then click Add Method.
  6. Set the Method access to public, set the Return type to void, and type PayRise for the Method name. Add a decimal parameter named amount and click Finish. This adds the following method to the class:
    public void PayRise(decimal amount)
    {
    }
    					
  7. Define the body of the method as follows:
    public void PayRise(decimal amount)
    {
       this.salary += amount;
    
    }
back to the top

Define Read-Write Properties

  1. In Class View, right-click the Employee class, click Add, and then click Add Property.
  2. Set the Property access to public, set the Property type to string, and type FullName for the Property name. Click the get/set radio button, and then click Finish. This adds the following property to the class:
    public string FullName
    {
       get
       {
          return null;
       }
       set
       {
       }
    
    }
  3. Modify the property as follows:
    public string FullName
    {
       get
       {
          return this.name;
       }
       set
       {
          this.name = value;
       }
    
    }
    The get accessor returns the employee's name. The set accessor sets the employee's name, using the implicit value parameter that is automatically passed into the set accessor.
back to the top

Define Read-Only Properties

  1. In Class View, right-click the Employee class, click Add, and then click Add Property.
  2. Set the Property access to public, set the Property type to decimal, and type Remuneration for the Property name. Click the get radio button, and then click Finish. This adds the following read-only property to the class:
    public decimal Remuneration
    {
       get
       {
          return 0;
       }
    
    }
  3. Modify the property as follows:
    public decimal Remuneration
    {
       get
       {
          return this.salary;
       }
    
    }
    The get accessor returns the employee's salary. There is no set accessor because the salary cannot be changed directly. The only way to change the salary is to call the PayRise method.

  4. Repeat steps 1 through 3 (or type the code manually) to add another get accessor. This get accessor should be called DaysSinceJoined, have public access, and use an int type.
  5. Code the body of the get accessor as follows:
    public int DaysSinceJoined
    {
       get
       {
          TimeSpan timespan = DateTime.Now - this.hireDate;
          return timespan.Days;
       }
    
    }
    The get accessor calculates how many days the employee has worked for the company.
back to the top

Create an Object and Use the Properties

  1. Display the code for Class1.cs in the Code View window.
  2. In the Main method, create an Employee object by using the new operator. Assign the object reference to a local Employee variable, as follows:
    Employee worker = new Employee( "Jayne Doe", 
                                    125000, 
                                    new DateTime(1998, 7, 31) );
    					
  3. Add the following code to change the employee's FullName property:
    worker.FullName = "Jayne Lafayette";
    This implicitly invokes the set accessor for the FullName property.

  4. Add the statements shown below to display the employee's details by using the get accessors for the FullName, Remuneration, and DaysSinceJoined properties:
    Console.WriteLine("Full name: " + worker.FullName);
    Console.WriteLine("Remuneration: " + worker.Remuneration);
    Console.WriteLine("Days since joined: " + worker.DaysSinceJoined);
    					
back to the top

Verify that the Application Works

  1. Build and run the application. The application displays the following information on the console (the Days since joined value depends on the current date):

    Full name: Jayne Lafayette
    Remuneration: 125000
    Days since joined: 1140
  2. Return to the Class1.cs file in the Code View window, and add the following code to the bottom of the Main method:
    worker.Remuneration = 1000000;
  3. Try to build the application. Note that you receive a compilation error because there is no set accessor for the Remuneration property. This means that Remuneration is a read-only property.
  4. Change the statement as follows:
    worker.salary = 1000000;
  5. Try to build the application again. Note that you receive another compilation error because the salary field is private. The only way to modify the employee's salary is by using the public PayRise method.
back to the top

Modification Type:MinorLast Reviewed:10/4/2006
Keywords:kbhowto KB308229 kbAudDeveloper