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 not throw any exceptions when converting the obj object to the IDataContainer
interface or 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.
dynamic dataContainer = obj;
C.
var dataContainer = obj is IDataContainer;
D.
var dataContainer = obj as IDataContainer;
Explanation:
answer A: application throws exception if can’t cast
answer B: it isn’t really a casting so it’s wrong answer.
in D: “as” return null if can not cast
D is correct because we can’t do a cast of a object to type Interface
D is a correct becouse to convert object into Idatacontainer as keyword is used.
D