Click here to Skip to main content
15,063,944 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all visitors
i have problem with array an object in vb.net
i have created class (class student)
public class student
      private  id as integer
      private name as string
      private gender as string

      public property SetID() as string
          Get
             return id
          end get
          set(Byval value as string)
               id=value
          end set
      end property
     public property SetName() as string
          Get
             return name
          end get
          set(Byval value as string)
               name=value
          end set
      end property

      public function Display() as string
          return id & vbTab & name
      end function
end class

At the form load Event I write like this:
dim obj() as new student' if i declare object like it will error coz array can't use with "New"
so i need to declare like this:
dim obj() as student
redim preserve
obj(0).SetID=1
obj(0).SetName="AAA"


if i write like this, i will error say that "The object that i declare not yet set"
I don't know where should i set key word "New" of my student class.


Please help me, if i want to use array with object like that How i can do?

Best Regards,
Posted

1 solution

First of all, why use an array and not a dynamic container ? Second, if you create an array of objects, that doesn't mean that the objects are there, they will be set to Nothing and you need to create each object as you add it to the array. Finally, if you have errors, post the actual error to us, not your understanding of it. That way, we can actually understand what's going on.
   
Comments
soeun tony 13-Jul-11 21:47pm
   
Thanks for ur reply
This is for code that i used at form load event
ReDim Preserve obj(2)
obj(0).SetID = 1
obj(0).SetName = "A"
obj(1).SetID = 2
obj(1).SetName = "B"
obj(2).SetID = 3
obj(2).SetName = "C"
The error like this:"Object reference not set to an instance of an object."
Best Regards,
Dr.Walt Fair, PE 13-Jul-11 23:26pm
   
Like CG mentioned, you need to initialize the objects. Declaring an array of objects just reserves space for the pointers to the objects and you need to actually create each object.

For example, insert obj(0) = New student before obj(0).SetID, etc.
soeun tony 14-Jul-11 1:54am
   
Thank for ur reply
Do you mean like this:
Dim obj(3) as student
redim preserve obj(3)
obj(0).SetID=1
obj(0).SetName="A"
obj(1).SetID=2
obj(1).SetName="B"

Please help me,I really want to know about this. Cos i'm the new for vb.net
Best Regards,

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900