Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Hello, Happy new year!

 

I need help with collections. I have an array of a class (all the same type of course), but I think an arraylist would better fit my needs, the problem is that the arraylist is a collection of objects and I want it to be a collection of the type of my class cList. because when I want to call a method or a property in the class I have to cast everytime to the type I want, Is there a way to cast the arraylist to know that the type will be always the same, something like (im dreaming...): Dim X as Arraylist of cList :D

Is there a way to do it, or another type of colection that can help??

 

'With arrays
Dim x() as cList
redim x(0)
x(0)=new clist
x(0).text="Hello"

'With arraylist
Dim x as new arraylist
x.add(new clist)
DirectCast(x.item(0),clist).text="Hello"
'I don't want to do the casting every time i use x.

 

 

Thanks,

Ronq.

  • Administrators
Posted

'Naff class to work with
Public Class TestClass
Public thing As String
Public Otherthing As Integer
End Class

'start of a collection of test classes
Public Class TestList
Inherits ArrayList

Public Shadows Sub Add(ByVal Test As TestClass)
	MyBase.Add(Test)
End Sub

Public Shadows Property item(ByVal Index As Integer) As TestClass
	Get
		Return DirectCast(MyBase.Item(Index), TestClass)
	End Get
	Set(ByVal Value As TestClass)
		MyBase.Item(Index) = Value
	End Set
End Property
End Class

 

should be a reasonable starting point for a collection class - you may need to override / shadow other functions depending on your requirements.

 

You can then use it similar to

Dim MyList As New TestList
Dim x As New TestClass

MyList.Add(x)

Dim y As TestClass

y = MyList(0)
'etc.

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

Posted

Thank you very much, I need more practice with OOP and overloading, I didn't even think of that.

I'm a VB programmer and every new thing I learn about .NET make me want never go back... :D

 

Bye,

Ronq.

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...