NullReferenceException when using custom get/set

0

I wrote a custom getter/setter for a property in a ViewModel that is set in the model. But I get a NullReferenceException at the first if-statement:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

public class PDILogisticsViewModel
{
    private string _PDIComment;

    public string PDIComment {
     set {
      this._PDIComment = value;
     }
     get {
      if (_PDIComment.Equals("1"))
       return "Technischer Defekt";
      else if (_PDIComment.Equals("2"))
       return "OK";
      else
       return "Sonstiges";
     }

} }

When I use this code, everything works fine:

public string PDIComment { get; set; }

I also tried to add a null-check to return an empty string when _PDIComment is null but when I do that, the program crashes:

The program '[17728] iisexpress.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'.

 public string _PDIComment;
        public string PDIComment 
        {
            set
            {
                _PDIComment = value;
            }
            get
            {
                if (_PDIComment == null)
                    return "";
                else if (_PDIComment == "1")
                    return "Technischer Defekt";
                else if (_PDIComment == "2")
                    return "OK";
                else
                    return "Sonstiges";
            }
        }

Any idea what the problem could be here?

c#
asp.net-core
asked on Stack Overflow Jun 12, 2020 by d00d • edited Jun 12, 2020 by d00d

1 Answer

1

Use == not .equals

This is C# not Java. You cannot use a . after a value that is null.

answered on Stack Overflow Jun 12, 2020 by JoelFan

User contributions licensed under CC BY-SA 3.0