Properties


Properties encapsulate the state of a component and are the essence of rapid application development (RAD). They allow users to customize components in a design-time environment. The property construct has been supported in Visual Basic for several editions but is not offered by object-oriented programming languages such as C++ and Java. (Properties in JavaBeans are supported indirectly by adherence to a naming convention for accessor methods .) The .NET Framework brings the ease of RAD programming to the object-oriented world by supporting properties as a first-class object-oriented programming construct.

We'll look at the property construct first. Then we'll look at naming guidelines for properties and the advantages of exposing properties.

The Property Construct

Properties are like smart fields that are accessed using fieldlike syntax but implemented using accessor methods. The following example illustrates a simple property construct that defines a Name public property in the Person class:

 publicclassPerson{  //Theprivatefieldbelowisnotpartoftheproperty //constructbutcontainsdatathatholdsthevalueof //theNameproperty. privatestring_name; publicstringName{  get  { return_name; }  set  { _name=  value;  } }  } 

The boldface elements ” get , set , and value ” are keywords in the C# property syntax. The compiler transforms the code in the get and set blocks into methods that are called property accessors . The get accessor ”also called the getter ”retrieves the value of the property, while the set accessor ”also called the setter ” assigns a value to the property. The value identifier denotes the implicit parameter that is passed into the setter.

C# does not have a keyword named property . However, Visual Basic .NET does use the Property keyword as shown in the following example, which shows the keywords in Visual Basic .NET property syntax in boldface:

 PrivateString_name Public  Property  Name()AsString  Get  Return_name End  Get Set  (ByValvalueAsString) _name=value End  Set  End  Property  

In contrast with C#, value in Visual Basic .NET is not a keyword in property syntax.

Although the get and set accessors are equivalent to methods, they cannot be invoked as methods in C# and Visual Basic .NET but are indirectly accessed by code that assigns or retrieves a property.

The syntax for setting a property is the same as that for setting a field. When you are setting a property, the assigned value must match the declared type of the property:

 PersonaPerson=newPerson(); aPerson.Name= "John";//TypeofNameisstring. 

The property construct allows you to abstract the storage and implementation of a property from the clients of your component. In our example, a private field holds the data for the Name property. While the backing data for a property is often a private field, the data could reside elsewhere ”for example, on disk or in a database ”or it could be generated dynamically, as in a property that returns the system time.

A property can define both the get and set accessors or just a single accessor. A property with only a get accessor is a read-only property, while a property with only a set accessor is a write-only property. Although the CLR allows write-only properties, the design guidelines for the .NET Framework discourage them. If your component needs a write-only property, you should implement a method instead of a property to provide the equivalent functionality.

A property can have any access level allowed by the runtime, including public, private, protected, or internal. In C# and Visual Basic .NET, the access level of a property applies to both accessors; it is not possible to have a different access level for each accessor.

Although the get and set accessors are not directly accessible as methods, they are semantically equivalent to methods. Furthermore, they can perform any program logic, be overridden, and throw exceptions. In the next two sections, we'll show you how to override a property and perform value checking in a property accessor.

Virtual Properties

You generally provide virtual (overridable) properties to allow derived classes to narrow the range of permissible values, alter associated metadata, or perform additional logic when the value of the property changes.

To make a property overridable, you must mark it with the virtual keyword in C# ”and the Overridable keyword in Visual Basic .NET ”in the class in which the property is first declared. Here's a C# example:

 publicclassAnyInteger{ privateint_number; public  virtual  intNumber{ get{ return_number; } set{ _number=value; } }  } 

Here's a Visual Basic .NET example:

 PublicClassAnyInteger Private_numberAsInteger Public  Overridable  PropertyNumber()AsInteger Get Return_number EndGet Set(ByValvalueAsInteger) _number=value EndSet EndProperty  EndClass'AnyInteger 

Overriding a property is similar to overriding a method. To override a property in a derived class, mark the property with the override keyword in C# and the Overrides keyword in Visual Basic .NET. Here's a C# example:

 publicclassNonNegativeInteger:AnyInteger{ public  override  intNumber{ get{ returnbase.Number; } set{ if(value<0){ thrownewArgumentOutOfRangeException("Thenumbercannotbelessthan0."); } base.Number=value; } }  } 

And here's a Visual Basic .NET example:

 PublicClassNonNegativeInteger InheritsAnyInteger Public  Overrides  PropertyNumber()AsInteger Get ReturnMyBase.Number EndGet Set(ByValvalueAsInteger) Ifvalue<0Then ThrowNewArgumentOutOfRangeException(_  "Thenumbercannotbelessthan0.") EndIf MyBase.Number=value EndSet EndProperty  EndClass'PositiveInteger 

If both property accessors are defined in the base class, you must override both accessors when overriding a property. If you want to override the logic in only one of the accessors, you can let the other accessor delegate to the base class, as the getter for the Number property does in the previous example.

Although virtual properties make it easier to extend your component, you should keep a few considerations in mind when you define virtual properties. A virtual property cannot be sealed (made nonoverridable) in a derived class. Virtual properties also have implications for versioning. Once you define a virtual property, you must mark the property as virtual in later versions of your component; otherwise , you could break existing derived classes.

Properties and Validation

Property accessors can perform error checking (validation) in addition to getting or setting a property. If a property value is not acceptable, an accessor should throw an exception. In the previous example, we saw a property whose setter throws an ArgumentOutOfRangeException exception when the value assigned to the property is not a positive integer.

A well-designed component should perform argument validation in its property setters. When a setter throws an exception, it flags an erroneous property assignment as soon as it is made. This helps identify the location in user code where the error occurred. If your setter accepts erroneous values, there could be undesirable side effects during program execution when the erroneous value of the property adversely affects the behavior of your component. If a property does not throw exceptions, it is much harder for the user of your component to debug and track the cause of the unexpected behavior.

The .NET Framework class library provides a number of exception types, such as ArgumentException , ArgumentNullException , and ArgumentOutOfRangeException . You should use the most appropriate exception type, along with meaningful error messages.

Naming Guidelines for Properties

To ensure that your naming scheme for properties conforms to that of the .NET Framework, follow these naming guidelines:

  • Use a noun or a noun phrase as a property name ”for example, Count , Font , or Size .

  • Use Pascal casing . In other words, capitalize the first letter of the property name and the first letter of each subsequent word in the name ”for example, MinimumLevel and ViewState .

Advantages of Properties

It is standard object-oriented practice to encapsulate your component's data. Therefore, it should come as no surprise that we recommend that you should not expose fields from your components but instead expose properties. Properties offer many benefits over fields:

  • Data hiding The storage and implementation of properties, unlike that of fields, is invisible to the user.

  • Validation The setter can perform logic to check whether the assigned value satisfies any constraints that are required by your program logic. This also enables better error tracking. You cannot implement validation when using a field.

  • Overriding Properties can be overriden, thus allowing a derived class to alter the property implementation of the base class.

  • Versioning Because the implementation of a property is hidden from the user, you can modify the implementation in future versions without breaking compatibility ”that is, without requiring any changes to user code.

  • Designer support When a user selects a component on the design surface of a visual designer, the component's properties are displayed in the property browser, but its fields are not. We'll look at design-time support in Chapter 15.

  • Data binding The data-binding architecture in ASP.NET and Windows Forms supports binding to properties but not to fields. We'll discuss data binding in Chapter 16, "Data-Bound Controls."

In general, because of just-in-time (JIT) optimizations, properties are no less performant than fields ”as long as the accessors get or set an underlying field without adding a significant amount of new logic.

In this section, we covered general concepts related to the property construct in the .NET Framework. In Chapter 7, "Simple Properties and View State," and Chapter 10, "Complex Properties and State Management," we'll discuss details specific to properties in ASP.NET controls. We'll also show you how to implement different types of properties, such as primitive, reference, and collection properties.

In general, you should implement properties to represent state (data). However, in some situations, you should implement methods instead of properties, as we'll describe in the next section.



Developing Microsoft ASP. NET Server Controls and Components
Developing Microsoft ASP.NET Server Controls and Components (Pro-Developer)
ISBN: 0735615829
EAN: 2147483647
Year: 2005
Pages: 183

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net