Saturday, December 20, 2008
Object casting convenience methods
This upcoming version of Milos has a nice little enhancement in the utilities namespace. The DataHelper class now has extension methods that make it very convenient to cast from object types (such as fields in DataSets) to their real types.
These helper methods are implemented as extension methods. To use them, you have to add this line of code at the top of your program:
Now, the extension methods are automatically available on all objects. For instance, you can do the following:
DataSet myDs = this.GetSomeDataSet(); // Assume that we somehow get a DataSet
DataRow row = myDs.Tables.Rows;
Guid myGuid = row["id"].ToGuidSafe();
string myString = row["name"].ToStringSafe().Trim();
int myInt = row["number"].ToIntegerSafe();
The main advantage here is that these methods always return valid values, even if the cast object is not valid. For instance, these methods are aware of System.DBNull and they also trap errors.
There are a number of different such methods, including the ability to cast to booleans, DateTime, decimal, and so forth (all common value types, basically).
Posted @ 2:03 PM by Egger, Markus (firstname.lastname@example.org) -