Suppose I have the following class...
public class Person {
public string Name { get; set; }
public string Nickname { get; set; }
}
...and I want to be able to check (separately) if the Name
or Nickname
properties start with an "a".
I could write two methods like this...
public bool NameStartsWithA(Person p) {
return p.Name.ToLower().StartsWith("a");
}
public bool NicknameStartsWithA(Person p) {
return p.Nickname.ToLower().StartsWith("a");
}
However, this violates DRY (not a big issue in this artificially simple example, but could be significant in the real world).
Searching around, it seems that the answer to this is to do the following...
public bool StartsWithA(Person p, Expression<Func<Person, string>> f) {
return f.Compile()(p).ToLower().StartsWith("a");
}
...which can then be called as follows...
bool b = StartsWithA(person, p => p.Name);
This works fine, but I want to know what the point of the Expression
is. If I remove it, and make the method look like this...
public bool StartsWithA(Person p, Func<Person, string> f) {
return f(p).ToLower().StartsWith("a");
}
...it seems to work just as well.
Is there any point to the Expression
? Looking at "Why would you use Expression> rather than Func?" it seems that the Expression
doesn't give me any benefit in this case (other than a weeny improvement in execution speed, which may or may not be significant depending on the scenario), as all I'm doing is executing it, not modifying it.