Are non disposed resources freed when an object is garbage collected?

I was posed this question, and while I believe I know the answer, I believe I should be 100% certain else I start spreading misinformation!

I have this object:

public class MyObj(){
    private SqlConnection conn;

    public MyObj(string connString){
        var stream = File.Open(@"c:\\file.txt");
        conn = new SqlConnection(connString);
    }
}

When this object is created, a file handle is associated with the file, and a connection to a database is created. Neither has Dispose called on it as they should.

When this object goes out of scope and is eventually garbage collected, are these two resources then released, or do they remain in memory?

Jon Skeet
people
quotationmark

When this object goes out of scope and is eventually garbage collected, are these two resources then released, or do they remain in memory?

Usually some type - often somewhat hidden from the public API - has a handle on a native resource, possibly via SafeHandle, and that's what ends up releasing the resource. It's possible to write code which doesn't do this, of course, in which case the native resources would only be released on process exit through the normal OS clean-up, but I'd expect any Microsoft-provided APIs to do the right thing.

Of course, you should still dispose of resources explicitly :)

people

See more on this question at Stackoverflow