Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How best to share an IDisposable object like SqlConnection with several methods in a class?

Tags:

c#

Sometimes I have several methods all of which connect to SQL Server. This means that all methods contain local variables of IDisposable types like SqlConnection.

What is the best way to reuse one sqlconnection object? Would it be to pass it in as a reference and have it as a class-level variable? Also, if I use it throughout methods, does it need to be passed in by ref and should the class implement idisposable to dispose of the variable?

Thanks

like image 732
GurdeepS Avatar asked Dec 12 '22 16:12

GurdeepS


1 Answers

When it comes to SqlConnection, connection pooling will come into play, so in this case the answer is - don't share.

In general, unless a disposable object is designed for sharing, I wouldn't try to share it. There might be some cleanup required before it can be reused without consequence.

like image 119
Oded Avatar answered Dec 15 '22 04:12

Oded