ByRef parameters for objects / reference types

T

tinman

Hi....

Assume Function A in an application calls Function GetSomeData in another
assembly..... which then is the prefered method to return the SqlDatareader
object back to Function A (and why ?).

Does the prefered option apply to all reference types ?

Option 1
*******
Public Function GetSomeData (ByRef dr as SqlDataReader) as Long

Option 2
*******
Public Function GetSomeData (ByVal dr as SqlDataReader) as Long

Option 3
*******
Public Function GetSomeData () as SqlDataReader


Is it better to pass "objects" ByVal or ByRef (from a performance
perspective) ?


Cheers!
 
M

Mattias Sjögren

which then is the prefered method to return the SqlDatareader
object back to Function A (and why ?).

Option 1 and 3 are the only two that let you return a new
SqlDataReader object. Option 2 only lets you modify an existing one.

Whether you should use 1 or 3 depends on if you're actually using the
Long return value in #1 for something useful or not.

Is it better to pass "objects" ByVal or ByRef (from a performance
perspective) ?

From a performance point of view I don't think it makes any
difference. Do whatever makes sense for the semantics of your method.
ByRef indicates that the parameter can be reassigned to refer to a new
object.



Mattias
 
J

Jay B. Harlow [MVP - Outlook]

Tinman,
Is it better to pass "objects" ByVal or ByRef (from a performance
perspective) ?
Do not code for performance first, code for "correctness" first. Code only
for performance when a specific routine via profiling has proven to have a
performance problem!

The "correct" thing to do is to pass all parameters ByVal unless you
explicitly need to by ByRef, you only need to pass ByRef when you are
changing the callers variable itself (not the contents of the object the
variable refers to, but the variable itself!).

Which appears is what you are really asking how to do, that is return an
object from GetSomeData. I would use Option 3 as its more obvious (when you
call it) that you are returning a DataReader. Option 2 will not return a
data reader (it accepts a data reader as input).

Option 1 can be used to return the object, however it has "side effects"
(you are returning a value from the function, plus returning a value in a
parameter). I rarely code Functions with ByRef parameters as its not obvious
what they are doing ("side effects" are not very "correct"). I would either
code a Sub with 2 ByRef parameters if I need two values back, or a function
that returned an object/structure with the two values. Depending on what the
second value is (an status perhaps) I would return it via more appropriate
means (an exception instead of a status).

Hope this helps
Jay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top