Skip to main content

ConditionalWeakTable, what does it do?

C#'s ConditionalWeakTable, what does it do?

C# has many lesser known features, some more useful than others, and one of them is the ConditionalWeakTable<TKey, TValue> (keep in mind that TKey and TValue must be reference types).
You can think of this type as a dictionary where the keys are weakly referenced, meaning that they won’t count when the GC checks if the object has to be collected. Additionally, when the keys do eventually get collected by the GC, that entry will get removed from the dictionary. This means that you can attach arbitrary objects to any object, allowing you to do something like this:

public static class Extensions
{
    private static ConditionalWeakTable<object, dynamic> Table = new ConditionalWeakTable<object, dynamic>();

    public static dynamic Data(this object obj)
    {
        if (!Table.TryGetValue(obj, out var dyn))
            Table.Add(obj, dyn = new ExpandoObject());

        return dyn;
    }
}

...

var myObject = "hello";
myObject.Data().Foo = "bar";

Assert.AreEqual(myObject.Data().Foo, "bar");

As you can see, this is a really powerful feature allowing you to add any data you want to any object, although it may also lead to some ugly code so beware! If you’re still not convinced, take a look at a StringBuilder extension class I built for a project:

public static class StringBuilderExtensions
{
    private class StringBuilderData
    {
        public int Indentation;
    }

    private static ConditionalWeakTable<StringBuilder, StringBuilderData> DataTable = new ConditionalWeakTable<StringBuilder, StringBuilderData>();

    public static StringBuilder AppendIndentation(this StringBuilder builder)
    {
        return builder.Append(new string(' ', DataTable.GetOrCreateValue(builder).Indentation * 4));
    }

    public static StringBuilder Indent(this StringBuilder builder)
    {
        DataTable.GetOrCreateValue(builder).Indentation++;
        return builder;
    }

    public static StringBuilder Unindent(this StringBuilder builder)
    {
        DataTable.GetOrCreateValue(builder).Indentation--;
        return builder;
    }
}

Which you would use like:

var builder = new StringBuilder();

builder.AppendIndentation().AppendLine("This is unindented")
       .Indent()
       .AppendIndentation().AppendLine("This is indented by one level")
       .Unindent()
       .AppendIndentation().AppendLine("This is unindented again");

Yes, you could just write your own StringBuilder-esque class, but where’s the fun in that!

This type is clearly not meant for day-to-day use but I’m sure there’s at least one situation where using this type is the best solution. One place where I think it could be useful is if you’re patching methods at runtime with something like pardeike’s Harmony and you want to store additional info on a patched method’s instance object.

Comments

  1. Great! But why we couldn't do the same with a standard dictionary? You said it is related to GC but I don't see the problem

    ReplyDelete
    Replies
    1. Because a regular dictionary holds a strong reference to the values and, most importantly in this case, keys. So if you finish using an object everywhere in your program, the dictionary will still hold a reference to it, preventing the GC from collecting it. This is very problematic as objects will keep piling up and using memory.

      Delete

Post a Comment

Popular posts from this blog

Hangfire: setup and usage

How to setup Hangfire, a job scheduler for .NET Installing Hangfire Setting up Hangfire Setting up storage MySQL Storage In-memory storage Running jobs Fire-and-forget jobs Delayed jobs Continuation jobs Recurring jobs ASP.NET Core job integration Conclusion Hangfire is a job scheduler for .NET and .NET Core that lets you run jobs in the background. It features various different job types: Fire-and-forget jobs are executed only once , shortly after creation. Delayed jobs are very similar to fire-and-forget jobs but they wait for a specified amount of time before running. Continuation jobs, which run after their parent job has finished . Recurring jobs, perhaps the most interesting of all, run repeatedly on an interval . If you like Unix’s cron you’ll feel right at home, as this kind of job lets you specify the job interval as a cron expression . If you have never used this I recommend crontab.guru , it has a live expression editor, as well as some examp...

How to observe and control Windows media sessions in C#

How to control Windows media sessions in C# If you use Windows 10 and play music, you’ll most likely come across this dialog at some point: This is the media overlay, and it appears whenever you’re playing music and press a media key or you change the volume. This dialog uses the GlobalSystemMediaTransportControls family of APIs available on the Windows 10 Runtime API since version 1809. This API is usually restricted to UWP applications, however, the introduction of .NET 5 and the ability to target specific platforms in the project’s TargetFramework has made it available for use in any kind of application, like WPF or regular console programs. Fetching information from the GSMTC API The API’s entrypoint is the GlobalSystemMediaTransportControlsSessionManager . This class allows you to fetch all the current active sessions, as well as whichever one Windows thinks is the current one. In order to be able to access this class at all you must first set your project’s TargetFramewor...