Back to the basics...
For reference types, one can do this:
SomeType someObject = firstObject as SomeType;
if (someObject == null)
{
// Handle the situation gracefully
}
else
{
// Do stuff
}
For value types, my understanding is that we have implicit conversions (no data loss), explicit conversions (needed if there's a risk of data loss), the Convert
class (a "conversion wrapper" I think) and also type-specific conversions (e.g. double x = Double.Parse("2");
), but I haven't found anything similar to the as
operator above.
So, my question is: does the framework provide with some method/operator/technique to do something along these lines:
if (!Convert.CanConvert(someValue, someValueType))
{
// Beware! Data loss can occur
}
else
{
// No data loss here
}
If not, can anyone out there suggest a solid approach to build one such CanConvert
method?
Thanks a lot!
EDIT(1): The user-case/problem is as follows: Given a something passed by the code's consumer (my other self, but that's irrelevant), (1) Check that something is a number (easy enough) and (2) Place something in the "smallest" numeric type where it fits without incurring in data loss.
Some background: the nature of what I'm trying to do is more mathematical than technical: I'm trying to see if/how I can fit existing numeric types into some sort of an algebraic hierarchy of the form Monoid=>Group=>Ring=>Field (or a simplified version thereof). While working on this, and not very sure how, "one thing led to another" and I found myself having to deal with type conversions...