C# 6.0 Null Propagation Operator & Property Assignment

后端 未结 3 1941
情歌与酒
情歌与酒 2020-12-03 20:43

This question has been completely overhauled in the interest of being thorough in explanation.

I have noticed what appears to be quite a poor limitation of

相关标签:
3条回答
  • 2020-12-03 21:09

    Try it like this...

    using System;
    
    namespace TestCon
    {
        class Program
        {
            public static void Main()
        {
    
            Person person = null;
            //Person person = new Person() { Name = "Jack" };
    
            //Using an "if" null check.
            if (person != null)
            {
                Console.WriteLine(person.Name);
                person.Name = "Jane";
                Console.WriteLine(person.Name);
            }
    
            //using a ternary null check.
            string arg = (person != null) ? person.Name = "John" : arg = null;
            //Remember the first statment after the "?" is what happens when true. False after the ":". (Just saying "john" is not enough)
            //Console.WriteLine(person.Name);
    
            if (arg == null)
            {
                Console.WriteLine("arg is null");
            }
    
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }
    public class Person
    {
        public string Name { get; set; }
    }
    

    }

    0 讨论(0)
  • 2020-12-03 21:20

    You're not the only one! SLaks raised this as an issue (now here)

    Why can't I write code like this?

    Process.GetProcessById(2)?.Exited += delegate { };

    and after it was briefly closed as "By design"

    the ?. Operator never produces an lvalue, so this is by design.

    someone commented that it would be good for property setters as well as event handlers

    Maybe add also properties setters into request like:

    Object?.Prop = false;

    and it was re-opened as a feature request for C#7.

    0 讨论(0)
  • 2020-12-03 21:29

    You can't use the null-propagation operator in this way.

    This operator allows to propagate nulls while evaluating an expression. It can't be used as the target of an assignment exactly as the error suggests.

    You need to stick to the plain old null check:

    if (a != null)
    {
        a.Value = someValue;
    }
    
    0 讨论(0)
提交回复
热议问题