C# Interview Questions on data type casting

Q : What do you mean by casting a data type?

Ans : Converting a variable of one data type to another data type is called casting. This is also called as data type conversion.

Q : What are the 2 kinds of data type conversions in C#?

Ans : 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.

Q :What is the difference between an implicit conversion and an explicit conversion?

Ans : 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.

Q : What type of data type conversion happens when the compiler encounters the following code?

Ans : 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.

Q : Will the following code compile?

Ans : 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.

Q : If you want to convert a base type to a derived type, what type of conversion do you use?

Ans : 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;

Q : What operators can be used to cast from one reference type to another without the risk of throwing an exception?

Ans : The is and as operators can be used to cast from one reference type to another without the risk of throwing an exception.

Q : If casting fails what type of exception is thrown?

Ans : InvalidCastException

Leave a Reply
Name (required)
Email (will not be published) (required)
Web Site

List of Top Hospitals in India