ReSharper is crazy
Mar 18
2012
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.
Discussion
denis
Hi i have had an .net exe written for me and have been using it for about 3 years... i am not a developer
but i do have questions and need some help here and there.......i was searching for an understanding of a line in my config file and saw some of your commentary
i wonder if you can help
i live in australia. kind regards denis
Svick
I'm sorry, I don't have much time lately, so I'm afraid I can't help you.
tobi
It must have been very much fun to write this R# transformation as a dev at Jetbrains.