Charles Okwuagwu
Charles Okwuagwu

Reputation: 10866

How to define an extension to overload the "+" Operator for performing simple array joining

Please how can we overload the "+" Operator for simple array joining convenience?

How can we define an extension to simplify this as below:

    Dim a = {1, 2}
    Dim b = {3, 4}
    Dim c = a + b ' should give {1, 2, 3, 4}

I get the error below:

'Error BC30452  Operator '+' is not defined for types 'Integer()' and 'Integer()'

Upvotes: 0

Views: 23

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460208

Duplicate of Overloading the + operator to add two arrays.

So since this is not possible (apart from using an extension) you could use this simple workaround using LINQ:

Dim c = a.Concat(b).ToArray()

Here's a possible implementation for an extension that works with arrays and lists as input and is more efficient than the LINQ approach:

<System.Runtime.CompilerServices.Extension()> _
Public Function Plus(Of t)(items1 As IList(Of T), items2 As IList(Of T)) As T()
    Dim resultArray(items1.Count + items2.Count - 1) As t
    For i As Int32 = 0 To items1.Count - 1
        resultArray(i) = items1(i)
    Next
    For i As Int32 = 0 To items2.Count - 1
        resultArray(i + items1.Count) = items2(i)
    Next
    Return resultArray
End Function

You can use it in this way:

Dim a = {1, 2}
Dim b = {3, 4}
Dim c = a.Plus(b)

Upvotes: 1

Related Questions