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
}
asked Oct 24, 2015 at 9:22
2
  • 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. Commented Oct 24, 2015 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. Commented Oct 24, 2015 at 10:48

2 Answers 2

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.

answered Oct 24, 2015 at 9:32
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.

answered Oct 24, 2015 at 9:33

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.