Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bang vs Default Property in Visual Basic

Tags:

c#

.net

vb.net

For a given class, with a default property of list, you can access an instance object in the list by doing myClass.defProperty("key"). You can also achieve the same results by typing myClass.defProperty!Key.

I have been told that using the parenthesis and quotes is faster for the way the runtime accesses the Property, but I'd like to understand what is the difference and how do each work...

I understand C# has a similar behavior by replacing the parenthesis with square brackets.

like image 945
PedroC88 Avatar asked Oct 07 '10 15:10

PedroC88


People also ask

What is a default property in Visual Basic?

A default property is a class or structure property that your code can access without specifying it. When calling code names a class or structure but not a property, and the context allows access to a property, Visual Basic resolves the access to that class or structure's default property if one exists.


1 Answers

Given the following code in Visual Basic.NET:

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

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

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

If you look at the IL under Reflector.NET then you'll find that they all translate 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 only lets you use statically defined keys that conform to the standard variable naming rules.

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

For code readability I would recommend the x.Item("Foo") notation as is is very clear as to what is going on. x("Foo") can be confused with a call to a procedure and x!Foo makes the Foo look like a variable and not a string (which it really is). Even the Stack Overflow color-coding makes the Foo look like a keyword!

The C# equivalent for this code is x["Foo"];. There is no ! syntax equivalent.

So, the bottom-line is that ! isn't better or worse on performance and just may make code maintenance more difficult so it should be avoided.

like image 84
Enigmativity Avatar answered Oct 04 '22 03:10

Enigmativity