Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

I have want to creata an array of objects but it seems to generate errors that I'm not familiar with.

 

Dim obj() As Object 'A Class

obj = new Object("Hello", 2) 'Default Constructor New(String, Integer)

 

It returns an error of:

An unhandled exception of type 'System.NullReferenceException' occurred in Program.exe

Additional information: Object reference not set to an instance of an object.

 

Any idea what did I do wrong?

  • Leaders
Posted
According to the code provided, you are assigning an object to a variable of type 1-dimensional array of objects. If you have option strict on, this will trigger a compiler error. If option strict is off, it should throw an invalid cast exception. My best guess is that you have option strict off and in addition to the invalid cast, you have an error that causes a null reference exception to be thrown in the constructor of your class. If you want more help, as plausibly damp said, you need to post more code (and maybe show us what line or function is causing the exception).
[sIGPIC]e[/sIGPIC]
Posted

Thanks for all your advise!

Like marble_eater said, I made mistake in declaring my array.

Should have been obj(10) instead of obj().

Is there any way to have an array that is not fixed in size?

  • Leaders
Posted

You can not change the array size. In VB6 (i don't know if it is available in .NET) there was redim and redim preserve which resized the arrays, but these actually created new arrays and if you used preserve it just copied the contents. In .NET if you want arrays that are variable in size, you have two options i can think of. You can use the System.Collections.ArrayList class, or when you want to resize an array, create a new one like this:

 

Dim X(8) As String

 

'RESIZE

X = New String (10) {}

 

'RESIZE AND PRESERVE

Dim NewX as New String(10) {}

Array.Copy(X, NewX, Math.Min(X.Length, NewX.Length))

X = NewX

[sIGPIC]e[/sIGPIC]

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...