Jakub Wisniewski
Jakub Wisniewski

Reputation: 2249

Add new item to Object Array

I have an object array containing objects with arrays. When i try to add another object later i get an error saying

'An exception of type 'System.MissingMemberException' occurred in     
 Microsoft.VisualBasic.dll but was not handled in user code
Additional information: Public member 'Add' on type 'Object()()' not found.'

And here is how i try to add new member

Dim data As Object = {
                   New Object() {"Year", "Sales", "Expenses"},
                   New Object() {"2004", 1000, 400},
                   New Object() {"2005", 1170, 460},
                   New Object() {"2006", 660, 1120},
                   New Object() {"2007", 1030, 540}
              }

Dim newObj = New Object() {"2008", 1030, 540}
data.Add(newObj)  'here the error occures

I tried changing data to List(of Object) and then it worked but the format of List is not acceptable later (i send data to different api as json).

Probably it's easy issue but i'am kind of newbie :) Thanks for help in advance.

Upvotes: 1

Views: 10413

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460078

The variable data is an Object. Object has no Add method. But since you actually declare it as Object()(an array of objects) you cannot use Add either because an array has a fixed size.

Instead use a List(Of Object) which can be resized:

Dim data As List(Of Object) = New List(Of Object) From
{
       New Object() {"Year", "Sales", "Expenses"},
       New Object() {"2004", 1000, 400},
       New Object() {"2005", 1170, 460},
       New Object() {"2006", 660, 1120},
       New Object() {"2007", 1030, 540}
}
// ...
data.Add(newObj)  

However, why do you use objects at all if you want to store strings? I would declare it as List(Of String), otherwise you always need to unbox to the same type that was boxed which is inefficient, less readable and more error-prone.

If you need an Object() you can use data.ToArray() when you're finished with it.

Upvotes: 1

Related Questions