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 IDataContainer;
C . var dataContainer = obj is IDataContainer;
D . dynamic dataContainer = obj;
Answer: A
Explanation:
direct cast. If object is not of the given type, an InvalidCastException is thrown.
Incorrect:
Not B: If obj is not of the given type, result is null.
Not C: If obj is not of a given type, result is false.
Not D: This simply check the variable during runtime. It will not throw an exception.
Reference: http://msdn.microsoft.com/en-us/library/ms173105.aspx