LP said:
thank you guys
I am a bit confused. On one hand SqlConnection is an object and passed by
reference (which is a "memory address" or "pointer") by default but on
another hand ref keyword passes in "a pointer"
Does ref keyword makes any difference when dealing with refernce types? What
am I missing here?
It's understandable you're confused. I understand what's happening and after
reading the explanations I'm confused.
Let's try it this way...
When you pass an object to a method using the default calling syntax, you are
always passing a copy of the reference to the object (the address).
If the method has the argument declared as ref, you are passing the address of
the address, meaning you could replace the original object. Let's look at a
couple of examples.
Let's say the connection argument is called "conn". In the called method if you
did:
conn.ConnectionString = "..."
The original object (the one you passed in) would have its connection string
changed regardless of whether it was passed by reference or by value.
The real difference comes in where your method creates a new object using the
same reference variable (pointer).
private void MyMethod( SqlConnection conn )
{
conn = new SqlConnection(...);
}
private void MyMethod( ref SqlConnection conn )
{
conn = new SqlConnection(...);
}
In the first example, there are now two SqlConnection objects, one pointed to by
the copy of the address and one pointed to by the original reference variable
(in the calling routine). When you return to the calling routine you would find
the original unchanged. You've said "Here's a copy of the original address to
the object. If you put a new address in its place that's cool, I still have the
original."
In the second example you're telling the framework to replace the original
connection object (the one passed in) with the new one. You've said "Here's
where you'll find the original pointer to the object. Please replace it with a
new pointer."
Yet another way to look at it is this:
a) Passing an object by value is like sending a fax. You've still got the
original in case someone screws up the faxed copy.
b) Passing an object by ref is like sending the original document by courier. If
they mark it up and send it back you've got no way to get back to the original.