USER-DEFINED TYPES AND AGGREGATES Listing 5-16: Exposing the

USER-DEFINED TYPES AND AGGREGATES Listing 5-16: Exposing the units Field of LDim public struct LDim : INullable { // public field can be accessed by SQL Server public string units; // rest of implementation } Listing 5-17 shows how the unitsfield can be accessed in a SQL batch. Listing 5-17: Accessing a Field of a User-Defined Type DECLARE @d AS LDim SET @d = CONVERT(LDim, 1 ft ) PRINT @d.units ft SET @d.units= miles The example shown in Listing 5-17 declares an LDim variable, sets its value to 1 ft , and then prints out the unit ft . It then sets the unitsfield to miles . Does this make sense? Miles is not one of the units that LDim supports. This implementation of LDimshows one of the traps into which it is easy to fall when exposing fields of the implementation of a user-defined type; this implementation is guaranteed to lead to corrupted data. The best practice is to never directly expose the fields of the implementation of a user-defined type, but to instead wrap those fields in a property so that you can validate any change made to that field. Listing 5-18 shows a best practice implementation of exposing the unitsfield of an LDim. Listing 5-18: Exposing units of LDim as a Property // used to recalculate value when units change private static double Factor(string units) { if (units == in ) return 1.0; if (units == ft ) return 12.0; if (units == yd ) return 36.0; return 1.0; } // property that wraps units in a SqlString public SqlString Units { // return is simple

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Adult Web Hosting services

Bookmark the permalink.

Comments are closed.