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.
5 using System
.Runtime
.Serialization
;
6 using System
.Runtime
.CompilerServices
;
7 using System
.Diagnostics
.CodeAnalysis
;
12 [System
.Runtime
.CompilerServices
.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
13 // This class is sealed to mitigate security issues caused by Object::MemberwiseClone.
14 public sealed partial class WeakReference
<T
> : ISerializable
17 // If you fix bugs here, please fix them in WeakReference at the same time.
19 // Creates a new WeakReference that keeps track of target.
20 // Assumes a Short Weak Reference (ie TrackResurrection is false.)
22 public WeakReference(T target
)
27 // Creates a new WeakReference that keeps track of target.
29 public WeakReference(T target
, bool trackResurrection
)
31 Create(target
, trackResurrection
);
34 private WeakReference(SerializationInfo info
, StreamingContext context
)
38 throw new ArgumentNullException(nameof(info
));
41 T target
= (T
)info
.GetValue("TrackedObject", typeof(T
))!; // Do not rename (binary serialization)
42 bool trackResurrection
= info
.GetBoolean("TrackResurrection"); // Do not rename (binary serialization)
44 Create(target
, trackResurrection
);
48 // We are exposing TryGetTarget instead of a simple getter to avoid a common problem where people write incorrect code like:
50 // WeakReference ref = ...;
51 // if (ref.Target != null)
52 // DoSomething(ref.Target)
54 [MethodImplAttribute(MethodImplOptions
.AggressiveInlining
)]
55 public bool TryGetTarget([MaybeNullWhen(false), NotNullWhen(true)] out T target
)
57 // Call the worker method that has more performant but less user friendly signature.
63 public void GetObjectData(SerializationInfo info
, StreamingContext context
)
67 throw new ArgumentNullException(nameof(info
));
70 info
.AddValue("TrackedObject", this.Target
, typeof(T
)); // Do not rename (binary serialization)
71 info
.AddValue("TrackResurrection", IsTrackResurrection()); // Do not rename (binary serialization)