Some C# code snippets for C# properties:

        /// <summary>
        /// A object property with null check
        /// </summary>
        private Type _propertyName = null;
        public Type PropertyName
        {
            get
            {
                if(_propertyName == null)
                {
                    throw new NullReferenceException("The property [MyClass.PropertyName] can't be null");
                }
                return _propertyName;
            }
            set
            {
                _propertyName = value;
            }
        }

        /// <summary>
        /// A string property with empty and null check
        /// </summary>
        private string _myString = null;
        public string MyString
        {
            get
            {
                if (string.IsNullOrEmpty(_myString))
                {
                    throw new NullReferenceException("The property [MyClass.MyString] can't be null");
                }
                return _myString;
            }
            set
            {
                _myString = value;
            }
        }

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.