Yes, definitely!
Although the garbage collector will (eventually) clean up managed
resources when they fall out of scope, you have very little control over
when that happens unless you call GC.Collect() explicitly. Contrary to
popular opinion, the garbage collector does not automatically clean up
managed resources as soon as they fall out of scope. Therefore, you might
think that calling GC.Collect() all the time is a good idea, but it
isn't - this will cause the garbage collector to collect *everything*
which has fallen out of scope, not just the resources that have fallen out
of scope of a particular piece of code, which is almost certainly
extremely inefficient... See this page for a discussion of this:
http://forums.whirlpool.net.au/forum-replies-archive.cfm/674562.html
You could use a try {} catch {} finally {} model where you dispose the
various ADO.NET objects in the finally {} section. This has the added
advantage that the objects will still be disposed even if an error occurs
in the try {} section. As it stands, your code has no exception handling
at all. This means that it is susceptible to memory leaks. E.g.
SqlDataSource ds = new dbase().getdatasource();
ds.SelectCommand = mainquery;
Repeater1.DataSource = ds;
Repeater1.DataBind();
If an exception is thrown for any reason by the second, third or fourth
lines above, the SqlDataSource object will remain in memory until the
garbage collector decides that it can clean it up. As stated above, this
may not be straightaway. This might not be too much of an issue in a
WinForms app, but in an ASP.NET with lots of concurrent users it could
potentially cause the web app to crash.
See here for an example of the SqlDataSource's Dispose() method being
called in a finally {} section:
http://msdn.microsoft.com/en-us/library/55b58dye.aspx The accompanying
code comment "// If anything strange happens, clean up" pretty much says
it all...
You can also use the using keyword for this scenario:
http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx
using (SqlDataSource ds = new dbase().getdatasource())
{
ds.SelectCommand = mainquery;
Repeater1.DataSource = ds;
Repeater1.DataBind();
}
However, although this means that the SqlDataSource object will be
collected even if an error occurs in the code contained within it, you
should still consider using proper exception handling.