Introducing Radical.sh

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

Explicit casting from object type with different datatype - Exceptional case in C#

The following code (Example 2) will throw exception because the object type is meant for only "LONG" type.
So, when you convert it to a string, exception will be raised.

Forget code explains this with two examples.
First one explains the proper explicit casting with long type.
Second one is the exceptional case.

Example 1:

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


Output:
124124



Example 2:

  1. using System;
  2. using System.Text;
  3.  
  4. namespace forgetCode
  5. {
  6.  
  7. class program
  8. {
  9. public static void Main()
  10. {
  11. // Assign long and then cast it to an object implictly.
  12. long value1 = 124124;
  13. object value2 = value1;
  14.  
  15. // Explicitly cast to string from the object type.
  16. //Error case
  17. // Unable to convert from "Long object type" to string
  18. string value3 = (string)value2;
  19. Console.WriteLine(value3);
  20.  
  21. }
  22. }
  23. }


Output:

Unhandled Exception: System.InvalidCastException: Unable to cast object of type
'System.Int64' to type 'System.String' at forgetCode.program.Main()