Bang vs Default Property in Visual Basic

For this class with the default property for the list, you can access an instance of the object in the list by running myClass.defProperty ("key"). You can also achieve the same result by typing the key myClass.defProperty !.

I was told that using brackets and quotes is faster for how the runtime accesses the Property, but I would like to understand what the difference is and how each work ...

I understand that C # has a similar behavior, replacing brackets with square brackets.

+6
source share
1 answer

Given the following code in Visual Basic.NET:

Dim x As New Dictionary(Of String, String) x.Item("Foo") = "Bar" 

You can access a member of the "Foo" dictionary using any of the following:

 Dim a = x!Foo Dim b = x("Foo") Dim c = x.Item("Foo") 

If you look at IL under Reflector.NET, you will find that they all go to:

 Dim a As String = x.Item("Foo") Dim b As String = x.Item("Foo") Dim c As String = x.Item("Foo") 

So, they are all equivalent in IL and, of course, they all execute at the same speed.

The bang operator allows you to use only statically defined keys that comply with standard variable naming rules.

Using indexed approaches, your keys can be almost any valid value (in this case a string), and you can use variables to represent the key.

To read the code, I would recommend the designation x.Item("Foo") , as it is very clear what is happening. x("Foo") can be confused with a procedure call, and x!Foo makes Foo look like a variable, not a string (actually this). Even the color coding of Qaru makes Foo look like a keyword!

C # equivalent for this code x["Foo"]; . No syntax equivalent ! .

So the bottom line is that ! not better or worse in performance and just might make code maintenance more difficult, so it should be avoided.

+5
source share

All Articles