C# 6.0 Null Propagation Operator & Property Assignment

江枫思渺然 提交于 2019-11-28 11:53:11

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.

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;
}

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; }
}

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!