U2U Blog

for developers and other creative minds

Extensions to get attribute information

Checking attributes on classes can be done by getting the type of the class and executing GetCustomAttributes() on it. You just need to iterate over the resulting object[] to find what you are interested in.

To simplify this a bit more, I wrote a couple of extension methods :

    static public class AttributeExtensions
        static public T FindAttribute<T>(this object obj)
            where T : Attribute
            return obj.GetType().GetCustomAttributes(true)
                .Where(attr => attr.GetType() == typeof(T))
                .Select(attr => attr as T).FirstOrDefault();

        static public List<Attribute> GetAttributes(this object obj)
            return obj.GetType().GetCustomAttributes(true).ConvertAllItems(c => c as Attribute).ToList();

        static private IEnumerable<TOutput> ConvertAllItems<TInput, TOutput>(this IEnumerable<TInput> e, 
            Converter<TInput, TOutput> op)
            foreach (TInput item in e)
                yield return op(item);

So, on a Person class like this

    public class Person
        public string Name { get; set; }
        public int Age { get; set; }

    Person p = new Person() { Name = "John Doe", Age = 77 } ;

You can now find the DataContractAttribute by:

    DataContractAttribute attribute = p.FindAttribute<DataContractAttribute>();
    Console.WriteLine(attribute != null ? attribute.Namespace : "Attribute not found");

Or, to retrieve the list of attributes:

    List<Attribute> lst = p.GetAttributes();

Silverlight 3.0 Hands-on workshop

On the 10th of September, Frederik and I will organize a Silverlight 3 hands-on workshop. In this workshop you will discover the new features of Silverlight 3

  • Out of browser
  • Navigation Framework
  • Animation easing
  • Pixel effects
  • Perspective 3D

This event is off course free of charge and will be hosted by boulevart at Schelle. Go to the BESUG site to subscribe you for the event.

Note: There are only 30 places, currently we have already 18 subscriptions, hurry up :-).


See the light

3 days.

Microsoft is building a lot of tension around the release of Silverlight 3. 3 more days, on the 10th of July it will be available.

With all the cool new features, even richer rich internet application will be possible.

You can follow it on http://www.seethelight.com.