Alex Rivera | Logout

Should we check NULL when cast IClass to Class?

Asked 2011-05-27T14:35:15.333
9

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

c#
Edit
Report

1 Answer

2

If you do NewClass n = (NewClass)obj you'll get an exception thrown if it doesn't cast properly.

If you want there to be a possibility of it being null, without throwing an exception, you'd want to do NewClass n = obj as NewClass; and then check if n is null.

You can check if a cast is going to work before hand, by using the is operator. if(obj is NewClass)

Hope this helps.

answered 2011-05-27T14:39:20.123

Your Answer