ObjectDisposedException.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Runtime.CompilerServices;
  5. using System.Runtime.Serialization;
  6. namespace System
  7. {
  8. /// <summary>
  9. /// The exception that is thrown when accessing an object that was disposed.
  10. /// </summary>
  11. [Serializable]
  12. [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
  13. public class ObjectDisposedException : InvalidOperationException
  14. {
  15. private readonly string? _objectName;
  16. // This constructor should only be called by the EE (COMPlusThrow)
  17. private ObjectDisposedException() :
  18. this(null, SR.ObjectDisposed_Generic)
  19. {
  20. }
  21. public ObjectDisposedException(string? objectName) :
  22. this(objectName, SR.ObjectDisposed_Generic)
  23. {
  24. }
  25. public ObjectDisposedException(string? objectName, string? message) : base(message)
  26. {
  27. HResult = HResults.COR_E_OBJECTDISPOSED;
  28. _objectName = objectName;
  29. }
  30. public ObjectDisposedException(string? message, Exception? innerException)
  31. : base(message, innerException)
  32. {
  33. HResult = HResults.COR_E_OBJECTDISPOSED;
  34. }
  35. protected ObjectDisposedException(SerializationInfo info, StreamingContext context)
  36. : base(info, context)
  37. {
  38. _objectName = info.GetString("ObjectName");
  39. }
  40. public override void GetObjectData(SerializationInfo info, StreamingContext context)
  41. {
  42. base.GetObjectData(info, context);
  43. info.AddValue("ObjectName", ObjectName, typeof(string));
  44. }
  45. /// <summary>
  46. /// Gets the text for the message for this exception.
  47. /// </summary>
  48. public override string Message
  49. {
  50. get
  51. {
  52. string name = ObjectName;
  53. if (string.IsNullOrEmpty(name))
  54. {
  55. return base.Message;
  56. }
  57. string objectDisposed = SR.Format(SR.ObjectDisposed_ObjectName_Name, name);
  58. return base.Message + Environment.NewLineConst + objectDisposed;
  59. }
  60. }
  61. public string ObjectName => _objectName ?? string.Empty;
  62. }
  63. }