1

I have a question about preferences. I have used and seen used both of these examples and was wondering if one is better/faster/preferred over the other...

Using SQL Server 2008 (RS = RecordSet)

RS!field

vs

RS.Fields("Field")

The first is shorter, quicker to type, but is there any advantage to one or the other?

D Stanley
  • 149,601
  • 11
  • 178
  • 240
Obfuscated
  • 311
  • 2
  • 15

1 Answers1

1

No, they are equivalent in VB. From the documentation:

Use the ! operator only on a class or interface as a dictionary access operator. The class or interface must have a default property that accepts a single String argument. The identifier immediately following the ! operator becomes the argument value passed to the default property as a string.

Since Fields is the "default" property for Recordset and Item is the default property for Fields,

RS!field

is compiled to

RS.Fields("field")

which is technically

RS.Fields.Item("field")

Note that you can also do

RS("field")

is one better/faster/preferred over the other?

Faster? No. Preferred? Well the latter usage is more consistent with other .NET languages, so it may be preferred in larger circles because of that.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • @Ben [this answer](http://stackoverflow.com/a/15958981/1081897) and the linked article within seem to indicate otherwise. I'm no VBA expert by any means, but I think we're just in a semantic argument which doesn't change the heart of the answer that the two syntaxes are equivalent. – D Stanley Sep 29 '15 at 13:13
  • But does it call `Collect` because that's the _default_ property (which is implemented by using the special `DISPID_COLLECT` attribute)? Or do _all_ classes that allow `!` have a `Collect` property? I can't find any official MS documentation that confirms either statement - only forums. But I still stand by the answer that they are equivalent, even if the actual mechanics of _why_ may be different. – D Stanley Sep 29 '15 at 13:37
  • Correction again: I just tried it in VBA and I was wrong. /hate it when that happens. – Ben Sep 30 '15 at 10:45