If I return a value inside the used block in the method, does the utility use the object before returning?

I am using old C # .NET code in an ASP.NET application, making sure that all SqlConnections are enclosed in using .

I know that using is the same as try / finally , where it places the object in finally > no matter what happens in try . If I have a method that returns a value inside using , although execution leaves the method when it is returned, does it still call .Dispose () on my object before / during / after it returns?

public static SqlCommand getSqlCommand(string strSql, string strConnect){ using (SqlConnection con = new SqlConnection(strConnect)) { con.Open(); SqlCommand cmd = GetSqlCommand(); cmd.Connection = con; cmd.CommandText = strSql; return cmd; } } 

Update: The accepted answer is the one that seems to me the best answer to my question, but note that this answer caught the stupidity of this code, that I am returning a command that uses a remote connection !: P

+4
source share
2 answers

Yes, it will still call dispose.

Run this very simple console application:

  class Program { static void Main(string[] args) { TestMethod(); Console.ReadLine(); } static string TestMethod() { using (new Me()) { return "Yes"; } } } class Me : IDisposable { #region IDisposable Members public void Dispose() { Console.WriteLine("Disposed"); } #endregion } 
+3
source

Yes. It will destroy your object. This will actually cause a problem in your code, as the returned SqlCommand depends on the SqlConnection , which will be deleted before the control flow returns to your caller.

However, you can use delegates to get around this. A good example for this is to rewrite your method as follows:

 public static SqlCommand ProcessSqlCommand(string strSql, string strConnect, Action<SqlCommand> processingMethod) { using (SqlConnection con = new SqlConnection(strConnect)) { con.Open(); SqlCommand cmd = GetSqlCommand(); cmd.Connection = con; cmd.CommandText = strSql; processingMethod(cmd); } } 

Then you can call it like this:

 ProcessSqlCommand(sqlStr, connectStr, (cmd) => { // Process the cmd results here... }); 
+9
source

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


All Articles