Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Casting from Object types within native types - Exception case in C#

The examples show how C# behaves strictly towards the object type conversions.


Example 1:
Normal conversion from int to long

  1. using System;
  2. using System.Text;
  3.  
  4. namespace forgetCode
  5. {
  6. class program
  7. {
  8. public static void Main()
  9. {
  10. int value1 = 124;
  11. long value2 = (long)value1;
  12. Console.WriteLine(value2);
  13. }
  14. }
  15. }


Output:
124


Example 2:
The following code throws exception even if casting is done between native types and with wide casting.

  1. using System;
  2. using System.Text;
  3.  
  4. namespace forgetCode
  5. {
  6. class program
  7. {
  8. public static void Main()
  9. {
  10. // Assign integer and then cast it to an object implictly.
  11. int value1 = 124;
  12. object value2 = value1;
  13.  
  14. // Explicitly cast to long again from the object type.
  15. //unProper casting
  16. long value3 = (long)value2;
  17. Console.WriteLine(value3);
  18.  
  19. }
  20. }
  21. }


Output:

Unhandled Exception: System.InvalidCastException: Specified cast is not valid at forgetCode.program.Main()