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

StackOverflow https://stackoverflow.com/questions/1153612

  •  18-09-2019
  •  | 
  •  

Question

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.

Was it helpful?

Solution

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

OTHER TIPS

How about:

z = Convert.ToDecimal(y);

Convert.ToDecimal(y);

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top