Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispose object that has been instantiated as method parameter c#

I have the following classes:

private static readonly string ConnectionString = "Dummy";
public static SqlConnection GetConnection()
{
    SqlConnection Connection = new SqlConnection(ConnectionString);
    return Connection;
}

public static SqlDataAdapter GetDataAdapter(string Query)
{
    SqlDataAdapter Adapt = new SqlDataAdapter(Query, GetConnection());
    return Adapt;
}
  • How do I dispose the SqlConnection object that is instantiated when GetConnection() is passed as parameter in my SqlDataAdapter constructor?
  • Will it get disposed automatically when I dispose my Adapt object in the method that called GetDataAdapter()?
  • If it's not possible to dispose it, how do you suggest to proceed?

Thanks for any help.

like image 383
Xeaz Avatar asked Nov 04 '22 08:11

Xeaz


1 Answers

Description

If you dispose your SqlDataAdapter it does not dispose the SqlConnection too because its not clear if you want to use the connection again. You have to change your design to get this done.

I suggest to pass the SqlConnection to the GetDataAdapter function.

Sample

static void Main(string[] args)
{ 
    using (SqlConnection connection = GetConnection()) 
    {
        using (SqlDataAdapter adapter = GetDataAdapter("YourQuery", connection)) 
        {

        }
        // SqlDataAdapter is disposed
    }
    // SqlConnection is disposed
}

private static readonly string ConnectionString = "Dummy";
public static SqlConnection GetConnection()
{
    SqlConnection Connection = new SqlConnection(ConnectionString);
    return Connection;
}

public static SqlDataAdapter GetDataAdapter(string Query, SqlConnection connection)
{
    SqlDataAdapter Adapt = new SqlDataAdapter(Query, connection);
    return Adapt;
}
like image 66
dknaack Avatar answered Nov 09 '22 07:11

dknaack