1

I'm trying to access a handle to a ::Collections::ArrayList with a two simple accessor/mutator functions:

/** --------------------------------------------
 * public accessor for RX message queue
 * --------------------------------------------- */
System::Collections::ArrayList^ peak_lib::rx_queue(void)
{
    return this->m_Queue_Mes_RX;
}
/** --------------------------------------------
 * public mutator for RX message queue
 * --------------------------------------------- */
void peak_lib::rx_queue( System::Collections::ArrayList^ inList )
{
if ( inList->Count != 0 ) // <-- error line
{
    this->m_Queue_Mes_RX = inList;
}
}

My compiler throws An unhandled exception of type 'System.NullReferenceException' occurred in my.exe and adds that the reference was not called on an object ( or something along these lines, I have to translate it from polish :/ ) when I try to access the ->Count property ( see error line in code ) as somebody told me to here to check if the inList variable exists.

What's the right (or at least a better :D) way to check if an ArrayList exists when I'm using C++/CLI Visual Studio 2008?

Community
  • 1
  • 1
Asmodiel
  • 1,002
  • 1
  • 12
  • 21

3 Answers3

2

Initially, check for null before checking for count

if (inList != nullptr)
{
     if(inList->count)
     {}
}
Paul
  • 26,170
  • 12
  • 85
  • 119
alexbuisson
  • 7,699
  • 3
  • 31
  • 44
1

Check for the null pointer before actually accessing its member.

if (inList)
{
     if(inList->count)
     {}
}

Also, as stated by Konrad in the comments, System::Collections::ArrayList is obsolete so try using vector instead

Saksham
  • 9,037
  • 7
  • 45
  • 73
1

A property setter should either set the property to the value passed or indicate an error. There are two ways to indicate an error: Either throw an argument exception (common) or change the object to an invalid state that is exposed in future operations with the object (rare, e.g., classes intended to be used with data binding).

It could be that setting the property to null should not be an error but your question implies you want to disallow that. So, passing null where a non-null list is expected is a Boneheaded Exception. It is something that should be corrected before release and not ignored by the called code or "handled" by the calling code.

Here's the check in that case:

if (inList == nullptr) throw gcnew ArgumentNullException(L"value");

On the other hand, passing an empty list doesn't seem exceptional at all. You should consider accepting an empty list as the property value. If that doesn't make sense, perhaps you should design your class without that read-write property and instead use a method and a read-only property or the like.

Other issues:

  • Consider Systems::Collections::Generic::List<T> instead of System::Collections::ArrayList
  • Consider exposing the list as a read-only collection.
Tom Blodget
  • 20,260
  • 3
  • 39
  • 72