Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET overload () operator

I am new to VB.NET and search for a method to copy the behaviour of a DataRow for example. In VB.NET I can write something like this:

Dim table As New DataTable
'assume the table gets initialized
table.Rows(0)("a value") = "another value"

Now how can I access a member of my class with brackets? I thought i could overload the () Operator but this seems not to be the answer.

like image 879
Pikkostack Avatar asked Oct 20 '14 11:10

Pikkostack


1 Answers

It's not an overload operator, this known as a default property.

"A class, structure, or interface can designate at most one of its properties as the default property, provided that property takes at least one parameter. If code makes a reference to a class or structure without specifying a member, Visual Basic resolves that reference to the default property." - MSDN -

Both the DataRowCollection class and the DataRow class have a default property named Item.

            |       |
table.Rows.Item(0).Item("a value") = "another value"

This allows you to write the code without specifying the Item members:

table.Rows(0)("a value") = "another value"

Here's a simple example of a custom class with a default property:

Public Class Foo

    Default Public Property Test(index As Integer) As String
        Get
            Return Me.items(index)
        End Get
        Set(value As String)
            Me.items(index) = value
        End Set
    End Property

    Private ReadOnly items As String() = New String(2) {"a", "b", "c"}

End Class

Dim f As New Foo()
Dim a As String = f(0)

f(0) = "A"

Given the example above, you can use the default property of the string class to get a character at specified position.

f(0) = "abc"
Dim c As Char = f(0)(1) '<- "b" | f.Test(0).Chars(1)
like image 80
Bjørn-Roger Kringsjå Avatar answered Oct 16 '22 18:10

Bjørn-Roger Kringsjå