1

I'm very new to coding and currently trying to learn C#. As a mini project/ practice I'm trying to create a mini address book, as part of that I want to calculate age from birthDate and today. My code to gather this date is as so:

DateTime today = DateTime.Today;
public int age(DateTime today, DateTime birthDate)
{   
    if (today.Month < this.birthDate.Month)
    {
        return ((today.Year - this.birthDate.Year) - 1);
    }
    else if (today.Month == this.birthDate.Month )
    {
        if (today.Day >= this.birthDate.Day)
            return (today.Year - this.birthDate.Year);
        else
            return ((today.Year - this.birthDate.Year) - 1);
    } 
    else
        return (today.Year - this.birthDate.Year);
}

However when I try to call a Console.WriteLine(person.age) or do anything with any of my person.age it tells me

The best overload method match for 'System.Console.WriteLine(string, params object[])' has some invalid arguments.

However as much as i've tried I can't work out what I have done wrong.

Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
Major
  • 146
  • 10
  • At the top of your code, you declare `DateTime today`, then you declare a method with a parameter 'DateTime today'. You should know that inside the method, the value of `today` will be what was passed to the method, not necessarily today's date. – Rik May 08 '14 at 11:15
  • See Also: [Handling Birthdays, and Other Anniversaries](http://codeofmatt.com/2014/04/09/handling-birthdays-and-other-anniversaries/) – Matt Johnson-Pint May 08 '14 at 16:34

4 Answers4

2

age is a method and you call it like a property.

Either do the following:

person.age(today, birthday);

or convert it to a property, which is probably what you want:

public int Age
{   
    get
    {
        var today = DateTime.Now;
        if (today.Month < this.birthDate.Month)
        {
            return ((today.Year - this.birthDate.Year) - 1);
        }
        else if (today.Month == this.birthDate.Month )
        {
            if (today.Day >= this.birthDate.Day)
                return (today.Year - this.birthDate.Year);
            else
                return ((today.Year - this.birthDate.Year) - 1);
        } 
        else
            return (today.Year - this.birthDate.Year);
    }
}
Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
2
Console.WriteLine(person.age(today, birthday).ToString());
Tomás
  • 535
  • 6
  • 23
0

It looks like you've forgotten to include the parameters, you've already for today initialised outside of your method but you'll also need one for Birthday then it's just a matter of passing it in:

person.age(today, birthday);
-1

The error suggests that you are passing wrong parameters or less parameters to the function. To resolve this you will have to modify as below

Console.WriteLine("The age of the person is {0}",person.age);

  • 1
    `person.age` is still a method used as a property, i.e. no parameters are supplied – Rik May 08 '14 at 11:16