Search code examples
c#linqnull-coalescing-operator

Assignment of property if not null, possible with null-coalecing?


I'm trying to do smth like

Im trying to assign property on an object if this object is not null. but standard form of non-null invocation does not work for assignment like this

socket?.Blocking = false

what I'm trying to do is shorten this if possible:

if(socket != null) socket.Blocking = false

Solution

  • This would be a great feature

    b?.c = "bob"
    

    Though, it's flawed when it comes to compound assignments. Consider this

    a.b?.c = "bob"
    

    What should it do on null?

    Personally, I think it should just ignore the parents. But alas, the powers that be have probably made the right decision to disallow this because of inconsistency with the other use cases of null conditional.

    Note : you could roll your own an extension method, though it's not very satisfying, and would probably fail my code reviews just on abstractness and readability.

    a?b.NullConditional(x => x.c = "bob"); 
    

    You are left with

    if(a?.b != null) a.b.c = "bob"
    

    or in your case

    if(socket != null) socket.Blocking = false
    

    or to write a dedicated extension method for this use case.