Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one check for "safe" conversions between value types in .NET?

Tags:

.net

math

algebra

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...

like image 934
d.. Avatar asked Jan 23 '10 18:01

d..


2 Answers

How about the TryParse method on the various value types?

int x;

if (int.TryParse(someType.ToString(), out x))
    return x;
like image 180
Rob Packwood Avatar answered Oct 12 '22 06:10

Rob Packwood


Henk is pretty much on the money. I'd like to add something to his answer, if I would:

Value-type conversion in the .NET Framework works using the IConvertible interface. The Convert class makes use of this for almost all of its methods. This is very different from implicit/explicit conversion operators in C#, which are merely another form of syntactic sugar.

If you write this:

public struct Duck
{
    public static implicit operator Goose(Duck d)
    {
        ...
    }
}

The .NET Framework itself has no idea that this exists. It is emitted as an op_implicit and it's up to the compiled language to figure out how to use it. Not every MSIL language actually supports these. So this code works:

Goose g1 = duck;

This code doesn't:

Goose g1 = (Goose)Convert.ChangeType(duck, typeof(Goose));

In order to implement a CanConvert method that is aware of implicit/explicit conversion operators, you would actually have to use Reflection to check for the individual op_ methods, and I'd have to recommend against doing that - I can see little use for it in practice.

like image 25
Aaronaught Avatar answered Oct 12 '22 06:10

Aaronaught