tags:

views:

274

answers:

4

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.

+8  A: 

How about:

z = Convert.ToDecimal(y);
Dmitry Brant
+1  A: 

Convert.ToDecimal(y);

Matt Jacobsen
+3  A: 

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

Mehrdad Afshari
A: 

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

Dan Diplo
That's not necessary, I know that my object is numeric. CType in vb would throw an exception, too, if it's not the case.
SchlaWiener