98-372 · Question #35
You are creating an application using .NET Framework 4.0. You write the following code segment in the application: BaseClass base = new BaseClass(); ChildClass child = (ChildClass)base; What type of e
The correct answer is B. InvalidCastException. A base class cannot be cast to a child class if that variable does not hold a reference to a child object. Therefore, the conversion causes the runtime to throw an InvalidCastException. InvalidCastException is the exception that is thrown for invalid casting or explicit conversio
Question
You are creating an application using .NET Framework 4.0. You write the following code segment in the application:
BaseClass base = new BaseClass(); ChildClass child = (ChildClass)base; What type of exception will the runtime throw for the above code segment?
Options
- AArgumentException
- BInvalidCastException
- CNotSupportedException
- DCastConvertException
How the community answered
(56 responses)- A7% (4)
- B75% (42)
- C4% (2)
- D14% (8)
Explanation
A base class cannot be cast to a child class if that variable does not hold a reference to a child object. Therefore, the conversion causes the runtime to throw an InvalidCastException. InvalidCastException is the exception that is thrown for invalid casting or explicit conversion. InvalidCastException is thrown if: A conversion is from a large to a small datatype. The source value is infinity, Not-a-Number (NaN), or too large to be represented as the destination type. A failure takes place during an explicit reference conversion. For an explicit reference conversion to be successful, the source value needs to be null, or the source argument referencing the object type must be convertible to the destination type by an implicit reference conversion. Answer: D is incorrect. There is no such exception as CastConvertException in NET Framework Answer: A is incorrect. The runtime throws an ArgumentException when you pass an invalid value to a method. Answer: C is incorrect. The runtime throws a NotSupportedException when there is an attempt to read, seek, or write to a stream that does not support the called functionality.
Topics
Community Discussion
No community discussion yet for this question.