Search code examples
c#equalitysettergetter

Check if class property has been set


Lets assume I have a User class

public Class User
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public int Level {get;set;}
}


User user1 = new User();
user1.Name = "name";
user1.Surname = "Surname";
user1.Level = 0;

User user2 = new User();
user2.Name = "name";
user2.Surname = "Surname";

When I check user1.Level == user2.Level it returns true since default int value is 0.

So is there any way to do that I can understand that Level property of user2 is not set so that I can say these two are not identical?


Solution

    1. If you use int? as type for Level, it will be NULL when not setted.
    public class User
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        public int? Level { get; set; }
    }
    
    1. You can use the setter of the Level attribute and set a boolean when you set a new value, if the other proposed solution is not good for you. Example:
    public class User
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        private int _Level;
        private bool _hasLevel;
        public int Level
        { 
            get { return _Level; } 
            set { _Level= value; _hasLevel = true; } 
        }
    
        public bool HasLevel { get { return _hasLevel; } }
    }