0

I have a class called Person which has properties Name, DateOfBirthand Age. Name and DateOfBirth are supplied when class instance is created but I want the Age property to be computed automatically as soon as the instance of class is created. I know how to do it using Parametrized Constructor but as I am trying to understand the power of Properties, I attempted following program but it is not giving expected output.

using System;

namespace Property
{
    class Person
    {
        #region private varaibles
        private int _age;
        #endregion

        #region properties
        public string Name { get; set; }
        public DateTime DateOfBirth { get; set; }
        public int Age
        {
            get { return _age; }
            set { _age = (DateTime.Now - DateOfBirth).Days / 365; }
        }
        #endregion properties
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person P = new Person() { Name = "Merin Nakarmi", DateOfBirth = new DateTime(1990, 1, 12) };
            Console.WriteLine("{0}, whose Date Of Birth is {1} is {2} years old!", P.Name, P.DateOfBirth, P.Age);    
        }
    }
}

The output I am getting is

enter image description here

I am expecting age to be 28. Help please.

Community
  • 1
  • 1
Merin Nakarmi
  • 3,148
  • 3
  • 35
  • 42
  • 1
    Yes, you need a read-only `Age` property as everyone has noticed. But you have another issue in your code, your `Age` property setter doesn't set the property from the right-hand side of an assignment; I'm surprised it complies. I somehow suspect that if you had assigned 5 to `Age` say: `P.Age=5;` before the WriteLine, then the Age property would have been assigned from `DateOfBirth` and you might have seen 28 and been very confused. Property setters always use the `value` keyword. – Flydog57 Sep 23 '18 at 02:27
  • 2
    As a side note, remember that not every year is 365 days, so you should factor in leap years if you want an accurate age. You can find a solution to that [here](https://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c). – ProgrammingLlama Sep 23 '18 at 03:00

2 Answers2

5

It seems you need a readonly age, if that's the case, you don't need to set anything in Age property, simply do:

    public int Age
    {
        get { 
               return DateTime.Now.Year - DateOfBirth.Year;
            }
    }

You may also want to have a look here and read a bit more on properties.
By the way as also @John pointed out concerning the correct calculation of the age(meaning taking leap years into account, you may want to have a look here)

Hossein
  • 24,202
  • 35
  • 119
  • 224
3

You are trying to read the property without setting it. So you can do both of these things in code like

get { return ((DateTime.Now - DateOfBirth).Days / 365); }
Hossein
  • 24,202
  • 35
  • 119
  • 224
Girish
  • 166
  • 1
  • 2
  • 13