Implicit Conversion: If a compiler converts one type of data into another type of data automatically, it is known as implicit conversions. There is no data loss in implicit conversion.
In implicit casting, conversion always takes place from lower to higher. Implicit is always under control of CLR. Here is an example of implicit conversion:
short a = 20; //Implicit conversion int b = a;
Explicit Conversion: When the data of one type is converted explicitly to another type with the help of some pre-defined functions it is called as explicit conversion and there may be data loss in this process because the conversion is forceful. These are some of the conversions that cannot be made implicit:
- int to short
- int to uint
- uint to int
- float to int
C#.Net supports following types of Explicit Type Casting.
- C++ Style Type Casting
C++ Style Type Casting: Here is the syntax for C++ style type casting.
datatype1 v1; datatype2 v2= (datatype2) v1;
Note: The type in parentheses is the target data type. There may be loss of data in casting process if you are casting to a smaller type. Here is an example showing casting:
int i = 257; byte sal = (byte)i; // gets max value of byte Console.WriteLine(byte.MaxValue.ToString()); //here possible for loosing the data Console.WriteLine(sal); Console.ReadLine();
Converting: Convert is a pre-defined class. Working with convert class is called as converting.
Methods of Convert class:
Convert.ToByte(); Convert.ToChar(); Convert.ToBoolean(); Convert.ToDateTime(); Convert.ToInt16(); Convert.ToInt32(); Convert.ToInt64();
Note: There is also method to convert between numeric values and strings in C#;
int x = 20; // x has been converted to string and its value will be as string '20' now string str = x.ToString();
Parsing: As per C#.Net all the datatypes are pre-defined structures. Structure is a collection of methods. Every datatype contains a set of methods as maxvalue, minvalue, parse(), Tostring()
string str = "20"; // Now the value of y is int '20' int y = int.parse(str);
Comments/Suggestions are invited. Happy coding......!