Type Conversions Implicit Conversion Explicit Conversion
Intro Value must be compatible with the variable. If not, we have to make a type conversion. Some data types can be converted to an other and some can not. We can lose data during unsafe conversion e.g. assigning a floating point number to an integer. In that case we lose fraction.
Implicit Conversions Numeric
Properties Occurs between compatible types. Transfers data from a smaller type to a bigger type. No data loss. No extra operation. Automatic type conversion.
Compatible types
Example Implicit Conversion No data loss
Explicit Conversion Numeric Character Character Numeric
Properties Occurs between incompatible types. May lose data. Extra coding needed. Use with caution.
Example
Exercise Assign a value to integer variable “source” that can not fit in to short type. Comment on the result.
Numeric Character.ToString() method. Can be used with numeric types. Converts numeric value to “ string ” type. There is also a formatting option.
Example Output : 123s
Formatting example “ NumberFormatInfo ” class. Used especially with floating point numbers. Resides under System.Globalization namespace. Formatting properties Number decimal digits Number decimal separator Number group separator
Formatting example Output: ,67
Character Numeric “ Convert ” class “ Explicit Conversion ” Used in conversion of multiple types. There should be compatible types between conversions.
Example Output: 132
Example – 2
Console.ReadLine() Used for getting input from screen. String type value is returned. Returns when user press Enter key. Later, return value can be converted to other types.
Console.ReadLine()