Properties are syntactic shorthand for accessor and mutator methods. In place of coding methods that retrieve or modify a particular member variable, properties provide both a get and a set submethod. Support for property style methods can be found in Visual Basic, C#, C++ (using __declspec()) and COM, to name a few. Consider the code snippet in Listing 2.2. Listing 2.2 Get/Set Methods1: class Person { 2: 3: private string name; 4: 5: public void SetName( string Name ) { name = Name; } 6: public string GetName( ) { return name; } 7: } 8: 9: Person me = new Person( ); 10: me.SetName( "Richard" ); 11: Console.WriteLine( me.GetName( ) ); The code in Listing 2.2 shows two methods whose sole purpose is to expose the underlying private data member: name. Before the notion of properties, this style of set/get methods for allowing access to data members was common practice among Object-Oriented developers. Without support for properties, accessing member fields requires the explicit invocation of a method. The property syntax merely shortens the code; however, the syntax offers a more natural expression. Listing 2.3 shows the same Person class using a property instead of methods to access the name member field. Listing 2.3 Properties1: class Person { 2: 3: private string name; 4: 5: public string Name { 6: get { return name; } 7: set { name = value; } 8: } 9: } 10: 11: Person me = new Person( ); 12: me.Name = "Richard"; 13: Console.WriteLine( me.Name ); The property syntax is shorthand notation for calling the accessor/mutator method. In fact, line 12 of Listing 2.3 is represented as me.set_Name( "Richard" ) in Intermediate Language and is the actual call made to the Person object. Controls have several properties already defined by the Control base class. These properties include Text, Size, ForeColor, BackColor, and a host of others. Table 2.1 shows some of the common properties of the Control base class.
Note At last count, the Control base class provides 59 properties of its own; for a complete listing of Control properties, see the MSDN help topic for Control Members. When creating new controls, you will also be defining additional properties that relate to the expected functionality of the control. The IconButton control developed in this chapter adds a property for the icon to be drawn on the button. Properties are in many respects the attributes of a control. As such, when deciding what properties a control should have, try to think in terms of "What are the attributes of this control?" With respect to the IconButton control to be developed, the Icon property defines the associated icon image of the control. |