Jürgen Steinblock
Jürgen Steinblock

Reputation: 31743

What's the best approach to solve the c# unboxing exception when casting an object to a valuetype?

I just converted a code snippet from VB.NET to C# and stumbled over this issue.

Consider this code:

    Dim x As Integer = 5
    Dim y As Object = x
    Dim z As Decimal = CType(y, Decimal)

No error from compiler or at runtime. z is five.

Now let's translate this code to C#

    int x = 5;
    object y = x;
    decimal z = (decimal)y;

No error from compiler but at runtime an exception is thrown:

    Cannot unbox "y" to "decimal"

Now my question is, which would be the smartest C# way to do this.

Currently my code looks like.

    int x = 5;
    object y = x;
    decimal z = decimal.Parse(y.ToString());

But another solution would be:

    decimal z = (decimal)(int)y;

Which looks a bit confusing, but propably has less overhead than decimal.Parse, I guess.

Upvotes: 4

Views: 5123

Answers (4)

Dan Diplo
Dan Diplo

Reputation: 25349

If you want to be totally safe you could try:

    int x = 5;
    object y = x;
    decimal z;
    if (Decimal.TryParse(y.ToString(), out z))
    {
        // z is a decimal
    }
    else
    {
        // z is not a decimal
    }

That way if someone sets y to = "donkey" you can handle it without throwing an exception. Of course, you may prefer to throw an exception if z cannot be converted. Just another option...

Upvotes: 0

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422112

(decimal)(int)x is the right way of doing so if you expect the boxed object to be an integer. Converting to string and parsing is not a good way to attack the problem and incurs some overhead.

If you just know the object can be converted to decimal in some way, try System.Convert.ToDecimal method. It'll handle that for you.

Upvotes: 7

Matt Jacobsen
Matt Jacobsen

Reputation: 5884

Convert.ToDecimal(y);

Upvotes: 2

Dmitry Brant
Dmitry Brant

Reputation: 7709

How about:

z = Convert.ToDecimal(y);

Upvotes: 10

Related Questions