Is using shared Dictionaries a good solution to the lack of "extension properties"?

c#, dictionary, extension-methods, inheritance

Solution

I'm not sure that is a good idea; the synchronization would be a nightmare, and you'd need to use a key that didn't risk keeping all the objects alive forever (don't use the object-reference). Better to use a property bag inside the object, or wrap your object in something else that provides the missing properties. You could also use inheritance, but that has more limitations (you can encapsulate a sealed type or an interface). You can forward the members if you really want:

public class Foo {
    private readonly Bar bar;
    public Foo(Bar bar) { this.bar = bar; }


    public int Id { get {return bar.Id; } set {bar.Id = value; } }
    public string Name {get;set;}
}

Problem

Suppose I have some extension methods but also need to extend the object's state. Seeing as there is no support for extension properties in C#, would using shared static Dictionary be a good solution? For example something like this: ``` class Foo { // 3rd party class } static class Helper { private static Dictionary<Foo, Guid> guidDict = new Dictionary<Foo, Guid>(); public static void DoSomething(this Foo foo) { Guid guid = guidDict[foo]; // do stuff } public static void DoAnotherthing(this Foo foo) { Guid guid = guidDict[foo]; // do stuff } } ``` What are some other solutions?

Original source