How do i create a code in C# that it tests age

Anonymous
2022-01-06T09:26:33.683+00:00

How do i create a simple code that tests if you are old (>29), getting old (19-30), a teenager (13-19) or a child <13)

i need to incorporate if statements

Developer technologies C#
{count} votes

2 answers

Sort by: Most helpful
  1. Sreeju Nair 12,666 Reputation points
    2022-01-06T13:24:02.473+00:00

    Based on your question, I assume, you have a DateTime object. See the following code that finds the age and compare it with DateTime.Now

    DateTime dob = new DateTime(2000, 1, 1);
    if(DateTime.Now.Year - dob.Year >29)
    {
        Console.WriteLine("You are old");
    }
    else if(DateTime.Now.Year - dob.Year > 19)
    {
        Console.WriteLine("You are getting old");
    }
    else if(DateTime.Now.Year - dob.Year > 12)
    {
        Console.WriteLine("You are teenager");
    }
    else
    {
        Console.WriteLine("You are a child");
    }
    
    0 comments No comments

  2. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-01-06T15:41:35.893+00:00

    Try this out.

    • Between works on int, decimal, DateTime
    • Note the IsChild extension, you can create others to e.g. IsAdult, IsTeenAger etc

    Code sample

    using System;
    using System.Collections.Generic;
    
    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
    
                int age = 29;
    
                Console.WriteLine($"{age,-3} {age.Between(30, 30)}");
    
                age = 30;
                Console.WriteLine($"{age,-3} {age.Between(30, 30)}");
    
                age = 30;
                Console.WriteLine($"{age,-3} {age.Between(19, 30)}");
    
                age = 12;
                Console.WriteLine($"{age,-3} {age.Between(1, 12)}");
    
                Console.WriteLine(age.IsChild().ToYesNoString());
    
                Console.Read();
            }
        }
    
        public static class GenericExtensions
        {
            public static bool Between<T>(this T value, T lowerValue, T upperValue) where T : struct, IComparable<T> 
                => Comparer<T>.Default.Compare(value, lowerValue) >= 0 && 
                   Comparer<T>.Default.Compare(value, upperValue) <= 0;
    
            public static bool IsChild(this int sender) 
                => sender.Between(1, 12);
    
            public static string ToYesNoString(this bool value) 
                => value ? "Yes" : "No";
        }
    }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.