Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment in lambda expression

Tags:

c#

I want to define some lambda expression that represent updates of properties of instances of a class.

I try to write that as below:

Expression<Action<User>> update = user => user.Name = "Joe Foo";

But I have a compilation error:

Error CS0832 An expression tree may not contain an assignment operator.

How to represent this update with a lambda.

EDIT

My goal is for a business service to send updates to a generic repository. This repository could analyze the expression of the lambdas to build query to send to the database engine.

An example of a business service could be:

public void DoStuff(String userId, ...)
{
  // Business logic here
  // ...

  // Persist updates determined above
  this.repository.Update(
    // First parameter is the filter of entities to updates
    x => x.Id == userId,
    // Next parameters are updates to apply
    x => x.FirstName = "John",
    x => x.LastName = "Foo",
    ...);
}
like image 364
gentiane Avatar asked Mar 13 '26 04:03

gentiane


1 Answers

I want to define some lambda expression that represent updates of properties of instances of a class.

You can't always get what you want.

We designed expression-tree lambdas to represent non-mutating operations, so using =, +=, ++ and so on in an expression-tree lambda is illegal.

How to represent this update with a lambda?

Delegate lambdas have no such restriction; you can say

Action<User> update = user => user.Name = "Joe Foo";

Can you say more about why you need this? There might be a better way to achieve your goal. You may be asking an XY question. That is a question where you have a problem, you have a bad solution, and now you are asking a question about the bad solution instead of about the problem. What's the problem you're trying to solve?

like image 98
Eric Lippert Avatar answered Mar 14 '26 17:03

Eric Lippert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!