dotnet / dotnet/dotnet-api-docs
Documentation for ConditionalWeakTable<TKey,TValue> is incorrect
- Dominant language
- C#
- Stars
- 949
- Forks
- 1.7k
- Avg merge
- 3d 27m
- Merged PRs (30d)
- 49
Description
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` because it does not compile properly.
This is the code snippet I'm talking about:
```cs
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();
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:
```cs
else if (cwt.TryGetValue(wr2.Target, out data))
```
and should be:
```cs
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
```
Contributor guide
Assessment
This issue has not been assessed yet.