ObjectDisposedException.cs 2.4 KB

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