Data type Conversions - Video
What do you mean by casting a data type?
Converting a variable of one data type to another data type is called casting. This is also called as data type conversion.
What are the 2 kinds of data type conversions in C#?
Implicit conversions: No special syntax is required because the conversion is type safe and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.
Explicit conversions: Explicit conversions require a cast operator. The source and destination variables are compatible, but there is a risk of data loss because the type of the destination variable is a smaller size than (or is a base class of) the source variable.
What is the difference between an implicit conversion and an explicit conversion?
1. Explicit conversions require a cast operator where as an implicit converstion is done automatically.
2. Explicit conversion can lead to data loss where as with implicit conversions there is no data loss.
What type of data type conversion happens when the compiler encounters the following code?
ChildClass CC = new ChildClass();
ParentClass PC = new ParentClass();
Implicit Conversion. For reference types, an implicit conversion always exists from a class to any one of its direct or indirect base classes or interfaces. No special syntax is necessary because a derived class always contains all the members of a base class.
Will the following code compile?
double d = 9999.11;
int i = d;
No, the above code will not compile. Double is a larger data type than integer. An implicit conversion is not done automatically bcos there is a data loss. Hence we have to use explicit conversion as shown below.
double d = 9999.11;
int i = (int)d; //Cast double to int.
If you want to convert a base type to a derived type, what type of conversion do you use?
Explicit conversion as shown below.
//Create a new derived type.
Car C1 = new Car();
// Implicit conversion to base type is safe.
Vehicle V = C1;
// Explicit conversion is required to cast back to derived type. The code below will compile but throw an exception at run time if the right-side object is not a Car object.
Car C2 = (Car) V;
What operators can be used to cast from one reference type to another without the risk of throwing an exception?
The is and as operators can be used to cast from one reference type to another without the risk of throwing an exception.
If casting fails what type of exception is thrown?