1

I was looking at some code at work and came across something I'm not familiar with.

here is full property im familiar with:

private int myVar;
public int MyProperty
{
    get { return myVar; }
    set { myVar = value; }
}

but then I saw (and I can't recall exactly) this:

private int myVar = x => x.Something;

This was found in application that uses CSLA.

Liger86
  • 57
  • 1
  • 8
  • Wanted to add that types of fields and properties were not int as in example above, they were custom types. – Liger86 Mar 27 '15 at 07:51
  • 6
    Does above code really compile? you are assigning anonymous function to a variable of type int? It does not seems to be possible. – Jenish Rabadiya Mar 27 '15 at 07:55
  • The above code is only to illustrate that I saw lambda assigned to field, and that it's foreign to me. – Liger86 Mar 27 '15 at 07:59
  • 1
    This looks like C#6 feature, but with wrong syntax. [Link](http://www.codeproject.com/Articles/857358/What-s-New-in-Csharp-Expression-bodied-Function) – Szer Mar 27 '15 at 08:35
  • the most obvious thing this is useful for is a *lightweight* dependency interjection - instead of having a (one-method) interface with an explicit implementation you can often just as easy use a delegate/`Func<...>` - this is just one of the great ideas swapping from functional programming into main stream OOP – Random Dev Mar 27 '15 at 09:58

4 Answers4

1

Using a lambda expression as a variable (public or private) is like using a function that can change.

for example i could do something like this

var myFavoriteFunction = (x) => x.FirstFunction();

//do some work
myFavoriteFunction(someobject)

//now change the function
myFavoriteFunction = (x) => x.SecondFunction();

myFavoriteFunction(someobject)

without knowing the code you are looking at, you might think of this as a click handler, and the function being executed when clicking the button can change. (of course a click handler you could also do differently but that's beside the point)

Batavia
  • 2,497
  • 14
  • 16
  • 2
    The first line is wrong, because the compiler can't know the type of `x` nor the final type of the delegate. Write it as: `Func myFav = x => x.FirstFunction()` – xanatos Mar 27 '15 at 08:36
  • 1
    @xanatos is right - but it's not because C# cannot infer the type but because it might either be a `Func<...>` or an `Expression>` - that's one price we have to pay so that LINQ works smother ;) – Random Dev Mar 27 '15 at 09:55
  • @CarstenKönig You are partially right... It can be seen with something like `var myvar = () => 5`. The error is the same. But on what you wrote I'll add that the compiler can't even know the exact type of delegate to use. In .NET there isn't an equivalency of delegates with same signature. So a `Func` is "different" that a `Predicate`, while both have the same signature down to the return type. – xanatos Mar 27 '15 at 10:02
  • @xanatos there *are* some .NET languages where this problem is (almost) *non-existent* ;) - should have written ".NET" and "will not" instead of "cannot" ^^ – Random Dev Mar 27 '15 at 10:04
1

Using expressions in this way is also called a property selector.

The correct syntax for this is actually like so.

private Expression<Func<Foo, int>> myVar = x => x.Something;

There are countless uses for these, and one typical example is to avoid having to "hard-code" member names that must otherwise be typed as string literals (which remain unchecked by the compiler and proves difficult to refactor).

Here's one practical application for this example.

Implementing INotifyPropertyChanged - does a better way exist?

You also see this heavily used in Fluent interface implementations, such as Fluent NHibernate.

In the advent of the nameof() expression coming in C# 6, however, we could soon see this technique fade.

http://davefancher.com/2014/12/02/c-6-0-nameof-expressions/

Community
  • 1
  • 1
Biscuits
  • 1,767
  • 1
  • 14
  • 22
  • 1
    If you want to discover the name of something, you would write it as `Expression> myVar` – xanatos Mar 27 '15 at 08:34
  • Thanks xanatos. You're right! I've amended accordingly. – Biscuits Mar 27 '15 at 08:47
  • 3
    @Biscuits: Even before the introduction of the `nameof` operator in C# 6, there is the `[CallerMemberName]` custom attribute (introduced with C# 5) which permits a better-performing alternative to the `Expression>`-based technique of retrieving a property's name. – stakx - no longer contributing Mar 27 '15 at 09:08
  • @stakx Thanks, I didn't know that. How do you see that being implemented in the INotifyPropertyChanged case, though? – Biscuits Mar 27 '15 at 09:13
  • 1
    @stackx `CallMemberName` has a specific and limited use. It works only if you can make the "thing" you want the name of call another function. It doesn't work if you want to be able to "describe" some properties/methods of a class – xanatos Mar 27 '15 at 09:19
  • @xanatos The CLR seems to get involved there. This is very cool! – Biscuits Mar 27 '15 at 09:35
  • 2
    @Biscuits No, it is entirely done by the compiler. Both `nameof` and `[CallMemberName]` are replaced by "constant" strings after compilation. – xanatos Mar 27 '15 at 09:38
1

Biscuits wrote about property (or field) selectors... There are two uses for these: one (the one he spoke about) to get the name of the field/property.

How to do it?

Given:

Expression<Func<Foo, int>> expression = x => x.Something;

You do:

string name = ((MemberExpression)expression.Body).Member.Name;

as written by others, in C# 6.0 this will become nearly useless thanks to nameof() (that in general is faster because it's done at compile time instead that at runtime) and in C# 5.0 partially useless thanks to [CallerMemberName].

The second use is that, by passing an Expression<> that is a "getter" (a function that given an object returns the value of something) to a method, the method can "build" a "setter".

Func<Foo, int> getter = expression.Compile();

var parameter = Expression.Parameter(expression.ReturnType);

Action<Foo, int> setter = Expression.Lambda<Action<Foo, int>>(
    Expression.Assign(expression.Body, parameter ), 
    new[] { expression.Parameters[0], parameter }).Compile();

Foo foo = new Foo();
setter(foo, 5); // Example of use of the setter
int value = getter(foo); // Example of use of the getter

If you have to use a single time the setter, this is quite slower than using directly reflection (because the Expressions must be built, then compiled and and so on, and in the building and compiling (but not in the using) of the Expression there is use of reflection). But if you need to use many times the getter/setter, then it become faster (if you "cache" them), because the use of a getter/setter built in this way is nearly as much fast as accessing the property/field directly (the slow part is in the creation of the getter/setter)

xanatos
  • 109,618
  • 12
  • 197
  • 280
0

What you saw was not related to a property, it was a delegate assignation. (The type was probably not an int)

Func<int,int> doubleMyNumber = (i) => 2 * i;

This works like a delegate, written as an anonymous function. More information here: https://msdn.microsoft.com/fr-fr/library/bb397687.aspx

In C# 6 you'll be able to see even stranger notations like this

public int AgeInDogYears() => Age * 7;

You'll be able to write the method's body as a lambda expression. http://csharp.2000things.com/2014/11/03/1217-using-lambda-expressions-for-function-members/

Nicolas C
  • 752
  • 5
  • 18