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

3

60

When implementing IDisposable, I undertand that every method that shouldn't be called after the object's been disposed should throw the ObjectDisposedException. But what is the standard for the name object that should be passed to the exception's constructor?

Names answered 26/12, 2009 at 22:7 Comment(0)
A
57

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.

Adoree answered 26/12, 2009 at 22:25 Comment(1)
Also, please see this question and my answer for general guidelines: #668940Adoree
O
15

Even the .NET Framework itself isn't very consistent here.

David M. Kean (former developer on the FxCop team at Microsoft) added a comment to the MSDN documentation for the ObjectDisposedException:

The typical usage of this type is something like the following:

[C#]
private void CheckDisposed()
{
    throw new ObjectDisposedException(GetType().FullName);
}
Orlina answered 26/12, 2009 at 22:26 Comment(3)
I missed it. Mut learn to read the comments in the documentation also.Names
@JonathonReinhart: The comment was obviously removed from the .NET 4-version of the page. I fixed the link above so it refers to the .NET 3.5-version which includes the quoted comment.Orlina
Might as well do throw new ObjectDisposedException(ToString());Veil
D
1

I don't believe there's a standard for that, I would return the type of the object along with the string content of a unique identifying field (a 'Primary Key' of sorts).

Donny answered 26/12, 2009 at 22:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.