I have a class called Person
which has properties Name
, DateOfBirth
and 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
I am expecting age to be 28. Help please.