Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we check NULL when cast IClass to Class?

Tags:

c#

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

like image 242
q0987 Avatar asked May 27 '11 14:05

q0987


2 Answers

When doing this:

NewClass n = (NewClass) obj;

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:

NewClass n = obj as NewClass;

then

if(n != null) ...

The cast you are doing is called a direct cast, where the system will assume that it can be made. the n = obj as NewClass is 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 is vs as in casting.

Depending on which scenario you want one will be better than the other. Technically from a performance perspective as is preferred. .Net will use atomically attempt to cast to the desired type and return null if it's not, where with is it 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:

var obj = o as type
if (obj != null)

as opposed to

if(o is type)
{
   var obj = (type); 
}
like image 165
kemiller2002 Avatar answered Oct 04 '22 10:10

kemiller2002


If the cast fails, your code will throw an exception.

Use the is operator to see if a cast will work, and as to cast (which will not throw and return a null if the cast fails).

So:

if(obj is NewClass)
{
  //Yay, can cast!
}

Or:

NewClass nc = obj as NewClass;
if(nc != null)
{
  //Yay!
}
like image 31
Oded Avatar answered Oct 04 '22 10:10

Oded