3

I want to compress this code:

if(obj != null)
{
     obj.Name = "Test";
}

If obj had a explicit method for setting the Name I could write

obj?.SetName("Test");

Is it possible to do so without a explicit method declaration?

Something like:

obj?.Name = "Test"; //assign obj.Name to "Test" if obj not null, do nothing if obj is null

The last statement gives the following error The left-hand side of an assignment must be a variable, property or indexer which kinda makes sense since (obj?.Name) is now a nullable boolean I believe.


Edit: this question seems a duplicate;

Using the null-conditional operator on the left-hand side of an assignment

Sturm
  • 3,968
  • 10
  • 48
  • 78

0 Answers0