Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

unboxing

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.

like image 832
Jürgen Steinblock Avatar asked Dec 01 '22 07:12

Jürgen Steinblock


1 Answers

How about:

z = Convert.ToDecimal(y);
like image 137
Dmitry Brant Avatar answered Dec 06 '22 11:12

Dmitry Brant