0

Is there any way I can assign to a property belonging to a member property, without using a conditional statement such as if? UIElement is a class and I am using nullable reference types.

For example:

public UIElement? Content { get; set; }
public override void LayoutChildren()
{
    Content.Size = Size;
}

However, if Content is null, then that will throw a null reference exception. I could, of course use:

if (Content is not null)
    Content.Size = Size;

But that requires a bulky and ugly if statement to do a simple thing.

What I want to achieve is something like this:

Content?.Size = Size;

Without using any helper methods (such as an AssignIfNotNull() method) or similar.

lostceiling
  • 63
  • 1
  • 7
  • Null conditional evaluates to something; can't be the target of an assignment – djv Dec 21 '21 at 19:50
  • @djv However you can use the null conditional operator for a method call (`SomeMember?.SomeMethod()`). If `SomeMember` evaluates to be null, it simply doesn't call the method. – lostceiling Dec 21 '21 at 20:18
  • 1
    @lostceiling Yes, same as calling a function without assigning to anything. But a function can't be the target of an assignment the same way. – djv Dec 21 '21 at 20:22

0 Answers0