Suggestion for With<T> content extension

Topics: General
Apr 8, 2011 at 4:21 AM

Had an idea for a simple extension to add to ContentExtensions.cs to along with As<T> and so on.

I find myself doing accessing a part to set a property e.g.:


var routePart = item.As();
if (routePart!=null) {
    routePart.Title = "Bar";

So I wrote an extension method that takes an action delegate instead:

        public static void With<T>(this IContent content, Action<T> action) where T : IContent
            T with = content.As<T>();
            if (with != null)

I can now just write this one-line version of the original example:

item.With<RoutePart>(r=>r.Title = "Bar");

Here's the IEnumerable<ContentItem> version as equivalent to AsPart<T>:

        public static void WithPart<T>(this IEnumerable<ContentItem> items, Action<T> action) where T : IContent
            foreach (var content in items.AsPart<T>())

So you can apply a delegate to a whole list of items at once.



Apr 8, 2011 at 5:37 AM
Edited Apr 8, 2011 at 5:39 AM

That's nice. There are probably some interesting things to explore with extension methods and fluent interfaces for content parts.