0

I have a class as below:

    class Member
    {
        public string Name { get; set; }
        public DateTime Birthday { get; set; }
        private int _age;
        public int Age
        {
            get { return _age; }
            private set { _age = DateTime.Now.Year - Birthday.Year; }
        }
    }

In the Main method, I assign member values and I want to get each member's age, but every result is zero, Why? How to solve this problem? Thanks!

    class Program
    {
        static void Main(string[] args)
        {
            List<Member> memberList = new List<Member>(); //using System.Collections.Generic;
            memberList.Add(new Member() { Name = "Andy", Birthday = new DateTime(1971, 7, 26)});
            memberList.Add(new Member() { Name = "Mike", Birthday = new DateTime(1982, 1, 17)});
            memberList.Add(new Member() { Name = "Lucy", Birthday = new DateTime(1993, 9, 28)});
            foreach (var m in memberList)
            {
                Console.WriteLine(m.Age); //m.Age = 0 
            }
        }
    }```
makelot
  • 19
  • 4

2 Answers2

1

Please return the age from getter method like this.

class Member
{
    public string Name { get; set; }
    public DateTime Birthday { get; set; }
    private int _age;
    public int Age
    {
        get { return DateTime.Now.Year - Birthday.Year; }
        private set { _age = DateTime.Now.Year - Birthday.Year; }
    }
}

You can remove the calculation from setter method.

Please see the output- enter image description here

Karthik96
  • 101
  • 1
  • 3
1

You need to update your class like this because the setter are not doing the operation since youre returning the variable on the get and thats why you got a 0 :

  public class Member
    {
        public string Name { get; set; }
        public DateTime Birthday { get; set; }
        public int Age
        {
            get { return DateTime.Now.Year - Birthday.Year;  }
            
        }
    }

after that change you can get the agre,btw you can calculate the age easier with a timespan to be more exact.

Cleptus
  • 3,446
  • 4
  • 28
  • 34
Daniel M
  • 36
  • 4
  • 1
    Empty setters are missleading. Don't make your coworkers get crazy thinking they can set something they cannot to later find out the setter did nothing. – Cleptus Jul 19 '22 at 06:20
  • 1
    Also, isn't `return _age = ...` a typo? – Cleptus Jul 19 '22 at 06:21
  • Simply `public int Age { get { return DateTime.Now.Year - Birthday.Year; } }` is OK! @Cleptus – makelot Jul 19 '22 at 15:03
  • @makelot yeah, I was pointing Daniel that the code was wrong – Cleptus Jul 19 '22 at 18:30
  • @makelot Also note that a year difference is not accurate to check the age. If your bday is in agoust, in January it would raise an incorrect value. Check the linked question to better answers – Cleptus Jul 19 '22 at 18:37
  • Thanks a lot! Yes, age is not just a simple minus calculation. @Cleptus – makelot Jul 20 '22 at 01:19