I really did no expect that.

ReSharper is crazy

While writing up an answer for a Stack Overflow question I had a code like this:

foreach (var property in sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
    if (!property.CanRead)
        continue;

    var targetProperty = targetType.GetProperty(property.Name, BindingFlags.Public | BindingFlags.Instance);
    if (targetProperty != null
            && targetProperty.CanWrite
            && targetProperty.PropertyType.IsAssignableFrom(property.PropertyType))
    {
        expressions.Add(
            Expression.Assign(
                Expression.Property(targetVariable, targetProperty),
                Expression.Convert(
                    Expression.Property(sourceVariable, property), targetProperty.PropertyType)));
    }
}

Nothing overly complicated, but not the simplest thing either. Then I noticed a green squiggly line under the foreach. Apparently, ReSharper can convert that code into a LINQ-expression. That's interesting, I wondered, how would the result look like? Like this:

expressions.AddRange(
    (from property in sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
        where property.CanRead
        let targetProperty = targetType.GetProperty(property.Name, BindingFlags.Public | BindingFlags.Instance)
        where
            targetProperty != null && targetProperty.CanWrite
            && targetProperty.PropertyType.IsAssignableFrom(property.PropertyType)
        select
            Expression.Assign(
                Expression.Property(targetVariable, targetProperty),
                Expression.Convert(Expression.Property(sourceVariable, property), targetProperty.PropertyType))).
        Cast<Expression>());

Okay, the final Cast() is unnecessary (and ReSharper itself knows that and offers you to remove it), but otherwise, great job!

In the end, I chose not to use LINQ here, but it's good to know the option is there and it's so easy.

c# resharper
Posted by: Petr Onderka
Last revised: 22 Sep, 2017 12:42 AM History

Discussion

Svick
Svick
07 Nov, 2012 11:04 PM

I'm sorry, I don't have much time lately, so I'm afraid I can't help you.

tobi
tobi
15 Jan, 2013 09:14 PM

It must have been very much fun to write this R# transformation as a dev at Jetbrains.

Your Comments

Used for your gravatar. Not required. Will not be public.
Posting code? Indent it by four spaces to make it look nice. Learn more about Markdown.

Preview