C#, WinForms: ListBox.Items.Add generates an OutOfMemoryException, why?

This is because of the way System.Windows.Forms.ListBox.NativeAdd method is implemented:

private int NativeAdd(object item)
{
    int num = (int) base.SendMessage(0x180, 0, base.GetItemText(item));
    switch (num)
    {
        case -2:
            throw new OutOfMemoryException();

        case -1:
            throw new OutOfMemoryException(SR.GetString("ListBoxItemOverflow"));
    }
    return num;
}

The GetItemText method uses ToString() on the object which returns null and so a message is sent with null parameter, which in turn returns an invalid pointer and you enter the second case which throws the exception.


When the underlying LB_ADDSTRING Windows API call fails, WinForms always returns an OutOfMemoryException. A comment in the .NET Framework Reference Source explains why:

// On some platforms (e.g. Win98), the ListBox control
// appears to return LB_ERR if there are a large number (>32000)
// of items. It doesn't appear to set error codes appropriately,
// so we'll have to assume that LB_ERR corresponds to item 
// overflow.
// 
throw new OutOfMemoryException(SR.GetString(SR.ListBoxItemOverflow)); 

Tags:

C#

Winforms