Question 1> Should I check NULL in the following case?
public interface INewClass {}
public class NewClass : INewClass {}
public void FunMeA(INewClass obj)
{
NewClass n = (NewClass) obj;
... // Should I check (n == null) here?
// call methods defined inside INewClass (updated from NewClass to INewClass)
...
}
A concrete example,
public void FunMeB(IAsyncResult itfAR)
{
AsyncResult ar = (AsyncResult) itfAR;
... // Should I check (ar == null) here?
// access ar.AsyncDelegate
...
}
Question 2> I just start to transfer to C# from C++.
When coding in C++, I know when the checking should be done.
However, I am totally lost in the C# world. So the question is: is there
a general rule that can tell me when I MUST check for NULL?
Thank you
When doing this:
There is no point, because if it doesn’t cast it will throw an invalid cast exception.
If you have any doubts as to whether or not you can actually cast it, you want to do:
then
The cast you are doing is called a direct cast, where the system will assume that it can be made. the
n = obj as NewClassis called an indirect cast and is for those scenarios where you want to tell the program “Hey I think this will work, but if not don’t flip out and throw an exception…I’ll deal with it if it doesn’t work.”Using
isvsasin casting.Depending on which scenario you want one will be better than the other. Technically from a performance perspective
asis preferred. .Net will use atomically attempt to cast to the desired type and return null if it’s not, where withisit will have to walk the inheritance tree twice to see if it matches that type and then cast it. So in most cases if you want to see if you want to cast and use that type it’s better to:as opposed to