1. Implicit conversion and explicit conversion
a) Implicit Conversion:
Implicit conversion is done by the compiler.1). When there is no loss of information and the size of target type is larger than the size of previous type.
2).If there is no possibilities of throwing the exception during the conversion
Example: Converting an type int to float type will not loose any data , no exception will be thrown hence an implicit conversion can be done.
Size of int is -2,147,483,648 to 2,147,483,647 and size of float is -3.4 × 1038 to +3.4 × 1038
Exp:
- using System;
- class implicitDemo
- {
- public static void Main()
- {
- int i = 100;
- float j=i;
- Console.WriteLine(j);
- }
- }
Fig: Screenshots of Output |
b). Explicit Conversion :
Example:
1.
- using System;
- class ExplicitDemo
- {
- public static void Main()
- {
- float f = 10987452135547895640.256F;
- float fi = 2558679458632566.1296F;
- int i = f;
- int j = fi;
- Console.WriteLine("{0}{1}", i, j);
- }
- }
Fig: Screenshots of Output |
2. Modified code
- using System;
- class ExplicitDemo
- {
- public static void Main()
- {
- float f = 100.256F;
- float fi = 256.1296F
- int i = (int)f; // Type cast Operator
- int j = Convert.ToInt32(fi); //using convert class
- Console.WriteLine("{0}{1}", i, j);
- }
- }
Fig: Screenshots of Output |
2. Parse() and TryParse()
If the number is in string format you have two option to convert them into another type one is Parse() and other is TryParse().
Parse() method throws an exception if it cannot parse the value, whereas TryParse() returns a bool indicating weather it succeeded or failed.
Use Parse() if you sure the value will be valid otherwise use TryParse().
Example 1. simple parse program
Example 1. simple parse program
- using System;
- class ParseDemo
- {
- public static void Main()
- {
- string strNumber = "100";
- int i = int.Parse(strNumber);
- Console.WriteLine(i);
- }
- }
Fig: Output of Parse() method |
Example 2. Parse() method throw an Exception if it cannot parse the value
- using System;
- class ParseDemo
- {
- public static void Main()
- {
- string strNumber = "100Sa";
- int i = int.Parse(strNumber);
- Console.WriteLine(i);
- }
- }
Fig: Unhandled Exception |
Example 3. TryParse() returns bool in case of failure
- using System;
- class ParseDemo
- {
- public static void Main()
- {
- string strNumber = "100San";
- int Result = 0;
- bool IsConversionSucessful = int.TryParse(strNumber, out Result);
- if(IsConversionSucessful)
- {
- Console.WriteLine(Result);
- }
- else
- {
- Console.WriteLine("Please enter a valid Number");
- }
- }
- }
Fig: Output of TryParse() |