0

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

}
  • Check this answer by Jon Skeet and also check the article he linked to. Passing by ref does not make sense unless you explicitly want to change the value of the passed parameter. – Andy Oct 24 '15 at 9:28
  • public static void (connection con) makes no sense in any language that I know of. There is no connection type, only a Connection type. Be accurate, Martin. – Mike Nakis Oct 24 '15 at 10:48
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.

2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.