It’s like the “Bag of Holding” for arrays

Here’s a little bit of code I find amusing. Haven’t you ever wanted an array that never ends? Or maybe better described as an array that loops? So if you have 10 items in your array and you ask for number 11, you get the first element again? I’m sure I have, but I don’t remember when or why.

Anyway, here’s a collection you can use for an (almost) infinite collection. It was actually a bit of trial and error to get the negative values to work properly.

Public Class ForeverCollection(Of T)
    Inherits Generic.List(Of T)

    Default Public Shadows ReadOnly Property Item(ByVal index As Integer) As T
            If Me.Count = 0 Then Throw New ArgumentOutOfRangeException("index")

            If index >= 0 Then
                Return MyBase.Item(Math.Abs(index Mod Me.Count))
                Return MyBase.Item(Me.Count - Math.Abs((index + 1) Mod Me.Count) - 1)
            End If

        End Get
    End Property
End Class

This uses the MOD operator which is a pretty fun bit of code. Its purpose is to return the leftover of any integer division. So 10 MOD 10 is 0, 12 MOD 10 is 2, 34 MOD 10 is 4. What good is that? Well, when you see the examples, it will make more sense.

You can use MOD for time calculations. You have 543 seconds on a timer. How many minutes and seconds is that? Which code is cooler?

allSecs = 543
min = 543 \ 60
sec = allSecs - (min * 60)
MsgBox(min & ":" & sec)or 

allSecs = 543
min = allSecs \ 60
sec = allSecs Mod 60
MsgBox(min & ":" & sec)

You can use MOD as a trigger. Lets say you have a counter and you want to annoy the user every X number of iterations.

For x As Integer = 1 To 1000
    If x Mod 15 = 0 Then
        MsgBox(String.Format("I've bugged you {0} time(s) " _
            & "and the counter is at {1}", (x / 15), x))
    End If

You can use MOD for pseudo-random seed data in SQL. MOD in SQL is "%". Take the milliseconds of the current time and mod it by different numbers.

declare @i int
set @i=0
while @i<500
    insert into userinfo(userid,createdate,logincount,
    select top 1 userid,getdate(),datepart(ms,getdate()),
        datepart(ms,getdate()) % 30,
        (datepart(ms,getdate()) % 15)*50,
        (datepart(ms,getdate()) % 25)*50,
        (datepart(ms,getdate()) % 10)*100
    from users
    order by newid()

    set @i=@i+1

I think of all the extra code I used to write before I discovered MOD and I think…