Introduction
Let's face it: strong-typing, while a great idea, can be a pain in the neck when trying to quickly access data that might be coming from not-so strongly typed environments. Introducing the concept of a null adds additional problems in an object-oriented language, where every thing is an object, and trying to do anything with a null
reference is ... well, I'm sure you know.
Most of the time, you want the value to be in a certain form, or if it's not in that form, you need to know that, to deal with it accordingly. Other times, you simply don't care about the data if it's not in the format you expect.
The System.Convert
namespace functions, while great at what they do, are still somewhat rigid to be truly useful, forcing you to write additional checks and exception handlers just to get at the data.
Overview
The SafeTypecast
library is nothing more than a layer between your data access logic and System.Convert
utilities, with several additions. It supports conversions to all standard data types (such as bool
, long
, int
, float
, etc.), standard extension types (unsigned long
s and int
s) and some other common types (DateTime
).
Most of the conversion functions also feature an equivalent overload that allows you to specify a value you would like to be returned, in case the actual conversions fails for any reason.
Below is a sample usage example:
using ulement.Utilities;
OleDbDataReader rdr = cmd.ExecuteReader();
if (rdr.Read()) {
long entry_id = SafeTypecast.ToLong(rdr["EntryID"]);
long author_id = SafeTypecast.ToLong(rdr["UserID"], -99);
DateTime datetimeposted = SafeTypecast.ToDateTime(rdr["DateTimePosted"]);
string message = SafeTypecast.ToString(rdr["Message"]);
bool is_active = SafeTypecast.ToBoolean(rdr["IsActive"]);
}
That's about it, really. Nothing mind-blowing, but definitely a good time and sanity saver.
Comments, questions and suggestions are always welcome.