[C++/CLI] testing a gcrooted member for null

B

bonk

I have a native class that has a managed private member:

private:
gcroot<MyManagedRefType^> m_managed;

Now at some point in time this member will eventually get initialized:

m_managed = gcnew MyManagedRefType();


How can test, wether this has already happend or not ? Without having to
catch the NullReferenceException (wich will be thrown if I try to access
Member of MyManagedRefType before the ctor was called).

if (m_managed)
if (m_managed != nullptr)

does not do the trick.
 
C

Carl Daniel [VC++ MVP]

bonk said:
I have a native class that has a managed private member:

private:
gcroot<MyManagedRefType^> m_managed;

Now at some point in time this member will eventually get initialized:

m_managed = gcnew MyManagedRefType();


How can test, wether this has already happend or not ? Without having
to catch the NullReferenceException (wich will be thrown if I try to
access Member of MyManagedRefType before the ctor was called).

if (m_managed)
if (m_managed != nullptr)

does not do the trick.

You have to cast it back to the managed type:

if (static_cast<MyManagedRefType^>(m_managed) == nullptr)
{
// it's null
}

-cd
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top