Tag property without inheritance

Tag property is very often used to store a data associated with an object. The simple way to add support for Tag property is to create a base class with the Tag property .I don’t like this solution – the reason is simple .Sometimes I want to inherit from an existing class that doesn’t have the Tag property and I can’t change its source code .In WPF we have dependency properties that can help us in this case.

MyControl cnt = new MyControl();
cnt.SetValue(FrameworkElement.TagProperty, new Info() );

One problem – we still need to inherit from DependecyObject class.

The helper class below uses extension methods – to provide the tag functionality for your classes.

Of course, for better performance, you may change the dictionary(and methods) to be more type specific .

/// Implements tag functionality
static class TagHelper
{

    /// Adds the tag
    public static void AddTag(this object element, object tag)
    {
        if (!Tags.ContainsKey(element))
        {
            Tags.Add(element, tag);
        }
    }

    /// Removes the tag for the specified element.
    public static void RemoveTag(this object element )
    {
        Tags.Remove(element);
    }

    ///
    /// Clears the tags.
    ///
    public static void ClearTags()
    {
        Tags.Clear();
    }

    /// Gets the tag for the specified element.
    public static object Get(this object element)
    {
        object tag;
        Tags.TryGetValue(element, out tag);

        return tag;
    }

    private static readonly Dictionary<object, object> Tags = new Dictionary<object, object>();
}

 
 
 

Leave a Reply