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.