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;
Ans. A
0
0
remember obj as Idatacontainer will never throw exception
0
0
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
0
0
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.
0
0
Artem is correct, question is wrong
0
0