views:

50

answers:

1

Hi there,

I come across some MC++ code like this:

__gc class ClassA
{
Puclic:
     ClassB GetClassB();
}

__gc class ClassB
{
 Public:
    int Value;
}

int main()
{
    ClassA^ a = gcnew ClassA();
    ClassB^ b = a->GetClassB();

    int c = b->Value;
}

Isn't it important to check whether b is NULL before access to its value? I tried if(b == NULL), but it dosen't work.

Or it's really not necessary to do the check? however I can hardly believe it...

Thanks.

Echo.

PS: I only want to know whether the "Reference" itself could be NULL here. Whether the content of class B is null isn't important.

+1  A: 

This program is both syntactically and semantically correct, as far as I can tell.

The reference COULD be null there, depending on the implementation of GetClassB(). So, technically, there could be a null-reference waiting to happen there.

However, if the contents of GetClassB() looks like this:

return gcnew ClassB();

you are guaranteed to either throw an exception or succeed, which means that the reference would never accidentally be null.

So, the real answer is: It depends, but you are never required to check for null.

To check for null use:

if (b == nullptr)
{
}
John Gietzen
Thanks so much for your quick answer :)The reason why I want to check NULL is that I didn't write both classes. They're included in .NET library. Since I can't tell what will really be returned if error happens, and don't want to throw exceptions "too frequently" at run time, so I would rather do the simple check at this point. :)E.
Echo
yes, what I forgot is, the exceptions could be thrown by ClassB here anyway, which I can't prevent :)
Echo