Chapter 3: Learning Just Enough C# and VB.NET: Types and Members

81

Coding Fields and Properties

A field is a variable that is a member of a class (type), as opposed to variables that are declared inside of methods, which are called local variables or locally scoped variables. Properties are type members that give you functionality that is a cross between fields and methods. You can read and write to a property just as you can to a field. Additionally, you can define code that runs whenever you read to or write from a property, similar to methods. The following sections define fields and properties.

Declaring and Using Fields

As stated, a field is a variable that is a member of a class (or some other container, such as a struct, which is very similar to a class). This provides the benefit of having the field and the data it contains available to all of the other members of the class (as well as to any deriving classes, via inheritance, depending on the field’s access modifier). To demonstrate how a field is declared and used, the example in Listing 3-8 simulates a bank account that has a field of type decimal named currentBalance, which holds an account balance. The class has two methods: Credit and Debit. Credit increases the value of currentBalance, and Debit decreases the value of currentBalance.

Listing 3-8 Using fields and properties

C#:

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

namespace FirstProgram

{

class Program

{

private decimal accountBalance = 100m;

static void Main(string[] args)

{

Program account = new Program(); account.Credit(100m); account.Debit(50m);

Console.WriteLine("Balance: " + account.CurrentBalance);

Console.ReadKey();

}

Page 104
Image 104
Microsoft 9GD00001 manual Coding Fields and Properties, Declaring and Using Fields, Listing 3-8 Using fields and properties