I have an object 'connection' which holds the path/credentials to a SQL DB.
When calling methods; we usually do this:
Connection con = new Connection();
GetSalesData(con);
public static void (Connection con)
{
// Run code
}
As I understand, we just created two instance of connection, so that means two memory allocations. Is it better to do this:
Connection con = new Connection();
GetSalesData(ref con);
public static void (ref Connection con)
{
// Run code
}
2 Answers 2
As I understand, we just created two instance of connection
No, we did not. Passing a variable automatically works as pass-by-reference for reference types and pass-by-value for value types. As your connection is a class, this means it is a reference type and only a reference will be passed to the method. You never created a second instance of your connection.
This has nothing to do with the static modifier, neither on the variable, nor on the method.
I suggest you spent a little while reading the MSDN on this topic, especially the two links called Passing Reference-Type Parameters and Passing Value-Type Parameters.
In addition, as another commenter remarked, you may want to read the excellent Jon Skeet on parameters.
When you use:
public static void GetSalesData (Connection con)
you are passing a reference to the Connection
object as a value. As such, you can access that object via con
. You aren't creating a second copy of the Connection
object.
Use:
public static void GetSalesData (ref Connection con)
you are now passing a reference to the memory location that in turn references the Connection
object. This lets you change what's in that memory location, ie you can change what con
in the code snippet:
Connection con = new Connection();
GetSalesData(con);
refers to. It is extremely unlikely that you want to do this.
ref
does not make sense unless you explicitly want to change the value of the passed parameter.public static void (connection con)
makes no sense in any language that I know of. There is noconnection
type, only aConnection
type. Be accurate, Martin.