DreamKid Posted March 13, 2005 Posted March 13, 2005 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? Quote
Administrators PlausiblyDamp Posted March 13, 2005 Administrators Posted March 13, 2005 Could you post a bit more code - at least show us the constructor of the class and where the error is happening. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
Leaders snarfblam Posted March 14, 2005 Leaders Posted March 14, 2005 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). Quote [sIGPIC]e[/sIGPIC]
DreamKid Posted March 14, 2005 Author Posted March 14, 2005 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? Quote
Leaders snarfblam Posted March 14, 2005 Leaders Posted March 14, 2005 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 Quote [sIGPIC]e[/sIGPIC]
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.