Microsoft KB Archive/308229

= How to define and use properties in Visual C# =

Article ID: 308229

Article Last Modified on 5/3/2007

-

APPLIES TO


 * Microsoft Visual C# 2005
 * Microsoft Visual C# .NET 2002 Standard Edition

-



This article was previously published under Q308229



In This Task

 * SUMMARY
 * Requirements
 * Create an Application that Contains a Visual C# .NET Class
 * Define Fields, Constructors, and Methods
 * Define Read-Write Properties
 * Define Read-Only Properties
 * Create an Object and Use the Properties
 * Verify that the Application Works



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.
 * 1) In the C# Add Class Wizard, set the Class name to Employee and click Open.
 * 2) Display the code for the new class in the Code View window.

back to the top

Define Fields, Constructors, and Methods
 In Class View, expand the EmployeeProperties project and expand the EmployeeProperties namespace. Right-click the Employee class, click Add, and then click Add Field.

Note In Visual Studio 2005, in Solution Expolorer, double-click ClassDiagram1.cd. Right-click the Employee class, and then click Class Details.  Set the Field access to private, the Field type to string, and type name for the Field name. Click Finish.

Note In Visual Studio 2005, in the Class Details - Employee panel, click the default text.

This adds the following field to the class: private string name;   Repeat steps 1 and 2 (or type the code manually) to add another two fields, as follows: private decimal salary; private DateTime hireDate;   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;

}  In Class View, right-click the Employee class, click Add, and then click Add Method.  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) { }                     Define the body of the method as follows: public void PayRise(decimal amount) {  this.salary += amount;

} </li></ol>

back to the top

Define Read-Write Properties
<ol> In Class View, right-click the Employee class, click Add, and then click Add Property.

Note In Visual Studio 2005, in Solution Expolorer, double-click ClassDiagram1.cd. Right-click the Employee class, and then click Class Details. In the Class Details - Employee panel, click the default text .</li>  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 {  }

} </li>  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. </li></ol>

back to the top

Define Read-Only Properties
<ol> In Class View, right-click the Employee class, click Add, and then click Add Property.

Note In Visual Studio 2005, in Solution Expolorer, double-click ClassDiagram1.cd. Right-click the Employee class, and then click Class Details. In the Class Details - Employee panel, click the default text .</li>  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; }

} </li>  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.

</li> 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.</li>  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. </li></ol>

back to the top

Create an Object and Use the Properties
<ol> Display the code for Class1.cs in the Code View window.</li>  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( &quot;Jayne Doe&quot;,                                125000,                                 new DateTime(1998, 7, 31) ); </li>  Add the following code to change the employee's FullName property: worker.FullName = &quot;Jayne Lafayette&quot;; This implicitly invokes the set accessor for the FullName property.

</li>  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(&quot;Full name: &quot; + worker.FullName); Console.WriteLine(&quot;Remuneration: &quot; + worker.Remuneration); Console.WriteLine(&quot;Days since joined: &quot; + worker.DaysSinceJoined); </li></ol>

back to the top

Verify that the Application Works
<ol>  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 </li>  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; </li> 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.</li> <li> Change the statement as follows: worker.salary = 1000000; </li> <li>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.</li></ol>

back to the top

Keywords: kbhowto KB308229

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.