Lesson10 PDF
Lesson10 PDF
Lesson10 PDF
LESSON 10 - PROPERTIES
B E G I N N E R S ’ S
C# TUTORIAL
1 0 . P R O P E R T I E S
WWW.CSHARP–STATION.COM
PAGE 1 OF 6
COPYRIGHT © 2000–2003 C# STATION , ALL RIGHTS RESERVED
BEGINNERS C# TUTORIAL
LESSON 10 - PROPERTIES
using System;
propHold.setSomeProperty(5);
return 0;
}
}
Listing 10-1 shows the traditional method of accessing class fields. The
PropertyHolder class has the field we're interested in accessing. It has two
methods, getSomeProperty() and setSomeProperty(). The
PAGE 2 OF 6
COPYRIGHT © 2000–2003 C# STATION , ALL RIGHTS RESERVED
BEGINNERS C# TUTORIAL
LESSON 10 - PROPERTIES
using System;
propHold.SomeProperty = 5;
return 0;
}
}
PAGE 3 OF 6
COPYRIGHT © 2000–2003 C# STATION , ALL RIGHTS RESERVED
BEGINNERS C# TUTORIAL
LESSON 10 - PROPERTIES
Listing 10-2 shows how to create and use a property. The PropertyHolder
class has the SomeProperty property implementation. Notice that the first
letter of the first word is capitalized. That's the only difference between
the names of the property SomeProperty and the field someProperty. The
property has two accessors, get and set. The get accessor returns the value
of the someProperty field. The set accessor sets the value of the
someProperty field with the contents of value. The value shown in the set
accessor is a C# reserved word.
using System;
PAGE 4 OF 6
COPYRIGHT © 2000–2003 C# STATION , ALL RIGHTS RESERVED
BEGINNERS C# TUTORIAL
LESSON 10 - PROPERTIES
return 0;
}
}
using System;
propHold.SomeProperty = 5;
return 0;
}
}
PAGE 5 OF 6
COPYRIGHT © 2000–2003 C# STATION , ALL RIGHTS RESERVED
BEGINNERS C# TUTORIAL
LESSON 10 - PROPERTIES
Listing 10-4 shows how to create and use a write-only property. This time
the get accessor is removed from the SomeProperty property of the
PropertyHolder class. The set accessor has been added, with a bit more
logic. It prints out the value of the someProperty field after it has been
modified.
In summary, you now know what properties are for and how they're
used. Traditional methods of encapsulation have relied on separate
methods. Properies allow you to access objects state as if it was a
field. Properties can be made read-only or write-only and you know how to
implement each type.
PAGE 6 OF 6
COPYRIGHT © 2000–2003 C# STATION , ALL RIGHTS RESERVED