What is the difference between these two C # methods

What is the difference between these two cases. First, if I open the connection and pass it to my method as a parameter, compared to opening the connection directly in the method?

cnn.open() func(cnn,param1,param2); 

against

 func(cnn, param1,param2) { cnn.open(); //open connection here } 
+4
source share
5 answers

There is no difference from the code you posted, except in one case, your calling function should take care of opening / closing the connection, and in the other you expect the function to do so.

+2
source

The difference is that in the second method, you open the connection.

In the first method, you expect that the method uses only the connection, without worrying about cleaning up the resources.

0
source

There is no functional difference, but the lines for opening and closing the connection should usually be as close to each other as possible, so they should be in the same method.

0
source

The difference is how you want to use the connection and performance. If the function is an open call, and you do not call any other functions or do nothing with the connection, then the second version of the function can even be reduced to:

 func(param1, param2) { Connection c = .... c.Open(...); ... c.Close(); } 

However, if you call many functions in the connection, even calling the function many times in the connection, or if creating and setting up the connection is at a higher level in your code, then you should use the first version with an exception if the connection does not open.

0
source

Well, I think you should not ask about something else, but rather explain the situation you are in and ask for recommendations about which case should be used.

In any case, as everyone told you. In case 2, the connection object and its life cycle are encapsulated inside the function of the called subscriber. This is recommended if the database operating system does not support this feature.

Otherwise, if you have any other database activity that will be performed outside this functional area, for example, in the caller function or any other function (other than func) called from the caller function, then you should use Case 1.

0
source

Source: https://habr.com/ru/post/1310346/


All Articles