Search code examples
c#propertiessetter

How to make a properly make setter edit class members


I am trying to make a setter for the public property of the private member age. It operates so that if the age you are trying to input is less than zero, the program should set it to zero and give you a basic message. However, this setter will literally let any negative number slip past it. If you try to edit it in the constructor, the setter doesn't even activate. But if you make an instance of the age class than try to edit that instances class, you can. However, it will let numbers less than zero pass through, and send the message "Viable", meaning it is a viable number. Here is the Person class the age member, property, constructor, etc. is located in.

 namespace HopeThisWorks
 {
     class Person
     {
        private int age;

        public int Age
        {
           get
           {
              return age;
           }
           set
           {
             if(age >= 0)
             {
                 age = value;
                System.Console.WriteLine("Viable");
             }
             else
             {
                 age = 0;
                 System.Console.WriteLine("Not Viable");
             }
          }
       }
       public Person(int age)
       {
           this.age = age;
       }
   }
}

Here is the main method:

using System;

namespace HopeThisWorks
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p1 = new Person(1);
            p1.Age = -1;
        }
    }
}

Any help would be muchly appreciated. Thank you!


Solution

  • Here's the working thing

    using System;
    
    public class Program
    {
        public static void Main()
        {
            var p = new Person(-5);
        }
    }
    
    class Person
    {
        private int _age;
        public int Age
        {
            get {return _age;}
            set
            {
                if (value >= 0)
                {
                    _age = value;
                    System.Console.WriteLine("Viable");
                }
                else
                {
                    _age = 0;
                    System.Console.WriteLine("Not Viable");
                }
            }
        }
    
        public Person(int age)
        {
            Age = age;
        }
    }
    

    In this case result will be Not Viable printed out.

    Explanation is in Mark's comment.