#1,210 – Exceptions in Property Accessors Can Be Ignored in Production Code

In the same way that binding errors are quietly swallowed in production code, exceptions originating in property getters or setters invoked as a result of WPF data binding can also be quietly ignored in production code.

Assume that we bind a TextBox.Text property to a string-based property in a ViewModel, as below. Note that when the data binding engine tries to set a property value of “Bob”, we’ll get a NullReferenceException.

        private BobNotify _bobNotify;

        private string _yourText;
        public string YourText
        {
            get { return _yourText; }
            set
            {
                if (SetProp(ref _yourText, value))
                {
                    // E-mail Bob if someone types his name
                    // (but we forgot to initialize BobNotify object, so will get NullRefException here).
                    if (_yourText == "Bob")
                        _bobNotify.SendEmail(_yourText);

                    RaisePropertyChanged("TextLength");
                }
            }
        }

        public int TextLength
        {
            get
            {
                return string.IsNullOrWhiteSpace(_yourText) ? 0 : _yourText.Length;
            }
        }

If we include this code in a release build and do nothing special to listen for binding errors, the exception will be quietly swallowed. The only hint that something went wrong is that the TextBlock that we bind TextLength to doesn’t get updated once we type the second “b” in “Bob”.

We can handle these sorts of errors in the same way that we did for other types of binding errors, by adding a binding error trace listener.