Mixing types in a Dictionary

I came over to C#.net from coldfusion years ago and one thing we can do in cf that is lovely is we can mix types in a dictionary without any unusual syntax. I recently found myself needing this feature in C# so I built the following class which can store the objects of the same family in the same dictionary. All in all it's a pretty good way to mix types however I'm sure someone else out there can do better.

public class AttributeContainer
{
        public AttributeContainer()
        {
            AttributeCollection = new Dictionary<string, Attribute>();
            AttributeTypeSafety = new Dictionary<string, Type>();
        }
        
        private IDictionary<string, Attribute> AttributeCollection { get; set; }
        private IDictionary<string, Type> AttributeTypeSafety { get; set; }

        public T GetAttribute<t>(string AttributeName) where T : Attribute, new()
        {
            T aType = new T();
            if (!typeof(T).IsAssignableFrom(AttributeTypeSafety[AttributeName]))
            {
                throw new InvalidCastException(string.Format("Attribute:'{0}' can not be cast to type:'{1}'", AttributeName, aType.GetType().ToString()));
            }
            return (T)AttributeCollection[AttributeName];
        }

        public void AddAttribute<t>(T attribute) where T : Attribute, new()
        {
            AttributeCollection.Add(attribute.AttributeName, attribute);
            AttributeTypeSafety.Add(attribute.AttributeName, attribute.GetType());
        }
}

No comments: