need help with c# conditions

Dani 1 Reputation point
2021-03-12T01:58:27.02+00:00

what's not ok?

i wanna create a age limit for my console app

what's the problem is with this code?
76860-damn-it.png

Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,596 Reputation points Volunteer Moderator
    2021-03-12T02:04:20.193+00:00

    Hello,

    Remove the semi-colon on the if statement, all you need is if (age > 18) no trailing semi-colon.

    76945-f1.png

    using System;  
      
    namespace ConsoleApp1  
    {  
        class Program  
        {  
            static void Main(string[] args)  
            {  
                var input = Console.ReadLine();  
      
                if (int.TryParse(input, out var age))  
                {  
                    Console.WriteLine(age > 18 ? $"You are over 18" : "You are not over 18");  
                }  
                else  
                {  
                    Console.WriteLine($"Invalid input {input}");  
                }  
            }  
        }  
    }  
      
    
    1 person found this answer helpful.
    0 comments No comments

  2. Sam of Simple Samples 5,571 Reputation points
    2021-03-12T02:31:31.977+00:00

    Karen is correct that you need to remove the semicolon. However that is not the cause of the red squiggly line under age > 18. The problem there is that age is a string and age > 18 is comparing the string to a number. You need to convert the string to a number before doing the comparison. If you have questions about the following then please first look at the documentation of TryParse.

    string age = Console.ReadLine();
    int intage;
    if (int.TryParse(age, out intage))
    {
        if (intage > 18)
            Console.WriteLine("Over 18");
        else
            Console.WriteLine("17 or under");
    }
    else
        Console.WriteLine("Invalid response");
    
    0 comments No comments

Your answer

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