Which code segment should you insert at line 07?

You are developing an application by using C#. The application includes the following code
segment. (Line numbers are included for reference only.)

The DoWork() method must throw an InvalidCastException exception if the obj object is not
of type IDataContainer when accessing the Data property.
You need to meet the requirements.
Which code segment should you insert at line 07?

You are developing an application by using C#. The application includes the following code
segment. (Line numbers are included for reference only.)

The DoWork() method must throw an InvalidCastException exception if the obj object is not
of type IDataContainer when accessing the Data property.
You need to meet the requirements.
Which code segment should you insert at line 07?

A.
var dataContainer = (IDataContainer) obj;

B.
var dataContainer = obj as IDataContamer;

C.
var dataContainer = obj is IDataContainer;

D.
dynamic dataContainer = obj;



Leave a Reply 5

Your email address will not be published. Required fields are marked *


vivek

vivek

remember obj as Idatacontainer will never throw exception

PaulC

PaulC

A is correct

Explanation:

A.
var dataContainer = (IDataContainer) obj ;- direct cast. If object is not of the given type, InvalidCastException is thrown

B.
var dataContainer = obj as IDataContamer; – if obj is not of the given type, result is null.

C.
var dataContainer = obj is IDataContainer; – if obj is not of a given type, result is false

D.
dynamic dataContainer = obj; – this simply check the variable during runtime. will not throw exception

Artem

Artem

Only A can throw InvalidCastException, but what about “when accessing the Data property”? With A it is not possible. D can throw exception “when accessing the Data property” but RuntimeBinderException.
Answer A, but question is not fully correct.

Anu

Anu

Artem is correct, question is wrong