Twinnaz
Twinnaz

Reputation: 44

Convert/Create a List (Of String) array to class or function

I have this code that phases a text file, formats it, and then creates a List(Of String) for each new line. Now what I want to do is create a class out of that List(Of String) so it can be accessed from anywhere in the program , and be able to pass it an integer parameter and it should return the string value of the integer index of the List(Of Strings). (I guess not sure if that's the right approach??) A bit confusing **

So for example: say I have the following

     Dim gcodelist As New List(Of String)

    Dim lines As String() = TextBox1.Text.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
    For Each l As String In lines
        gcodelist.Add(l)
    Next

I want to be able to turn that code into a class so that in Main sub() I can just call for example

   Sub Main() 
   MsgBox(Gcodeblock(5))
   End Sub

And it should print gcodelist(5) of the List (Of String) array to the msg box

Upvotes: 0

Views: 922

Answers (1)

Dave Doknjas
Dave Doknjas

Reputation: 6542

Create a class Gcodeblock, with an indexer (the 'Item' method):

Public Class Gcodeblock
    Private gcodelist As New List(Of String)

    Public Sub New(ByVal text As String)
        Dim lines As String() = text.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
        For Each l As String In lines
            gcodelist.Add(l)
        Next
    End Sub

    Default Public ReadOnly Property Item(ByVal index As Integer) As String
        Get
            Return gcodelist(index)
        End Get
    End Property
End Class

and use it like this:

Dim GcodeblockInstance = New Gcodeblock(yourText)
MsgBox(GcodeblockInstance(0))

My example uses a readonly indexer, but there's no reason you couldn't make it writable (remove the 'ReadOnly' keyword and add a 'Set' block).

Or you can inherit from List(Of String):

Public Class Gcodeblock
    Inherits List(Of String)

    Public Sub New(ByVal text As String)
        Dim lines As String() = text.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
        For Each l As String In lines
            MyBase.Add(l)
        Next
    End Sub
End Class

Upvotes: 1

Related Questions