Professional Documents
Culture Documents
Implicit Conversion:
compiler converts one type of data into another type of data automatically
In implicit casting, conversion always takes place from lower to higher
Implicit is always under control of CLR
example of implicit conversion
short a = 20; //Implicit conversion
int b = a;
Explicit Conversion:
data of one type is converted explicitly to another type with the help of some
pre-defined functions
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.
1. C++ Style Type Casting
2. Converting
3. Parsing
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;
255
byte sal = (byte)i;
1
// gets max value of byte
Console.WriteLine(byte.MaxValue.ToString());
//here possible for loosing the data
Console.WriteLine(sal);
Console.ReadLine();
2. Converting:
Convert is a pre-defined class.
Working with convert class is called as converting.
Methods of Convert class:
1. Convert.ToByte();
2. Convert.ToChar();
3. Convert.ToBoolean();
4. Convert.ToDateTime();
5. Convert.ToInt16();
6. Convert.ToInt32();
7. 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);
using System;
class Program
{ a is less than 20
static void Main(string[] args) value of a is : 10
{ /* local variable definition */
int a = 10;
/* check the boolean condition using if statement */
if (a < 20) /* if condition is true then print the following */
Console.WriteLine("a is less than 20");
Console.WriteLine("value of a is : {0}", a);
Console.ReadLine(); }}}