Question

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.

Was it helpful?

Solution

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);
    }
}

OTHER TIPS

Console.WriteLine(person.age(today, birthday).ToString());

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);

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);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top