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 .
/// <summary>
/// Implements tag functionality
/// </summary>
static class TagHelper
{
/// <summary>
/// Adds the tag.
/// </summary>
/// <param name="element">The element.</param>
/// <param name="tag">The tag.</param>
public static void AddTag(this object element, object tag)
{
if (!tags.ContainsKey(element))
{
tags.Add(element, tag);
}
}
/// <summary>
/// Removes the tag for the specified element.
/// </summary>
/// <param name="element">The element.</param>
public static void RemoveTag(this object element )
{
tags.Remove(element);
}
/// <summary>
/// Clears the tags.
/// </summary>
public static void ClearTags()
{
tags.Clear();
}
/// <summary>
/// Gets the tag for the specified element.
/// </summary>
/// <param name="element">The element.</param>
/// <returns></returns>
public static object Get(this object element)
{
object tag;
tags.TryGetValue(element, out tag);
return tag;
}
private static Dictionary<object, object> tags =
new Dictionary<object, object>();
}
Technorati Tags:
c#,
dotnet,
snippet