dotnet / dotnet-api-docs

.NET API reference documentation (.NET 5+, .NET Core, .NET Framework)
https://docs.microsoft.com/dotnet/api/
Other
722 stars 1.56k forks source link

Documentation for ConditionalWeakTable<TKey,TValue> is incorrect #8418

Open jeroenvervaeke opened 2 years ago

jeroenvervaeke commented 2 years ago

Page in the documentation: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.conditionalweaktable-2

I was about to create a PR for the code snippet on the page about ConditionalWeakTable<TKey,TValue> because it does not compile properly.

This is the code snippet I'm talking about:

using System;
using System.Runtime.CompilerServices;

public class Example
{
   public static void Main()
   {
      var mc1 = new ManagedClass();
      var mc2 = new ManagedClass();
      var mc3 = new ManagedClass();

      var cwt = new ConditionalWeakTable<ManagedClass, ClassData>();
      cwt.Add(mc1, new ClassData());          
      cwt.Add(mc2, new ClassData());
      cwt.Add(mc3, new ClassData());

      var wr2 = new WeakReference(mc2);
      mc2 = null;

      GC.Collect();

      ClassData data = null; 

      if (wr2.Target == null)
          Console.WriteLine("No strong reference to mc2 exists.");   
      else if (cwt.TryGetValue(wr2.Target, out data))
          Console.WriteLine("Data created at {0}", data.CreationTime);      
      else
          Console.WriteLine("mc2 not found in the table.");
   }
}

public class ManagedClass
{ 
}

public class ClassData
{
   public DateTime CreationTime;
   public object Data;   

   public ClassData()
   {
      CreationTime = DateTime.Now;
      this.Data  = new object();     
   }
}
// The example displays the following output:
//       No strong reference to mc2 exists.

This line is incorrect:

else if (cwt.TryGetValue(wr2.Target, out data))

and should be:

else if (cwt.TryGetValue((ManagedClass)wr2.Target, out data))

However, after running the code in the example the output I got was:

Data created at 9/23/2022 10:04:09 AM

Instead of the desired

No strong reference to mc2 exists.

I'm not sure if this is a bug in dotnet or not, however the documentation is not in sync with the actual result so I decided to create a PR here.

Dotnet version:

dotnet --version
6.0.300
dotnet-issue-labeler[bot] commented 2 years ago

I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.

joperezr commented 2 years ago

Thanks for opening the issue @jeroenvervaeke . Since you have a repro and have worked out the fix, would you be willing to submit a Pull request with the fix?