yield return statement inside a using() { } block Disposes before executing

When you call GetAllAnimals it doesn’t actually execute any code until you enumerate the returned IEnumerable in a foreach loop. The dataContext is being disposed as soon as the wrapper method returns, before you enumerate the IEnumerable. The simplest solution would be to make the wrapper method an iterator as well, like this: public static … Read more

Should you implement IDisposable.Dispose() so that it never throws?

The Framework Design Guidelines (2nd ed) has this as (ยง9.4.1): AVOID throwing an exception from within Dispose(bool) except under critical situations where the containing process has been corrupted (leaks, inconsistent shared state, etc.). Commentary [Edit]: There are guidelines, not hard rules. And this is an “AVOID” not a “DO NOT” guideline. As noted (in comments) … Read more

What should be passed as the objectName when throwing an ObjectDisposedException?

I believe the recommended practice is to throw the following: throw new ObjectDisposedException(GetType().FullName); Or including the check, these two lines of code at the top of each method that needs it (obviously not the Dispose method itself): if (this.disposed) throw new ObjectDisposedException(GetType().FullName); Might even be helpful to refactor this into a tiny method for usability.

Is there any benefit to implementing IDisposable on classes which do not have resources?

There are only 2 reasons for implementing IDisposable on a type The type contains native resources which must be freed when the type is no longer used The type contains fields of type IDisposable If neither of these are true then don’t implement IDisposable EDIT Several people have mentioned that IDisposable is a nice way … Read more

When or if to Dispose HttpResponseMessage when calling ReadAsStreamAsync?

So it seems like the calling code needs to know about and take ownership of the response message as well as the stream, or I leave the response message undisposed and let the finalizer deal with it. Neither option feels right. In this specific case, there are no finalizers. Neither HttpResponseMessage or HttpRequestMessage implement a … Read more

Who should call Dispose on IDisposable objects when passed into another object?

P.S.: I have posted a new answer (containing a simple set of rules who should call Dispose, and how to design an API that deals with IDisposable objects). While the present answer contains valuable ideas, I have come to believe that its main suggestion often won’t work in practice: Hiding away IDisposable objects in “coarser-grained” … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)