C# User Input

User input is essential for interactive applications. In C#, we can receive user input using the Console.ReadLine() method, which allows users to enter data via the keyboard. This guide will cover how to take input from users, process it, and handle different data types.

1. Taking Input from Users

Example: Getting a String Input

To take input from the user and store it in a variable:

using System;

class Program {
    static void Main() {
        Console.Write("Enter your name: ");
        string name = Console.ReadLine(); // Reads input from the user
        Console.WriteLine("Hello, " + name + "! Welcome to The Coding College.");
    }
}

Output:

Enter your name: Naman
Hello, Naman! Welcome to The Coding College.

2. Taking Integer Input

By default, Console.ReadLine() reads input as a string, so we must convert it to an integer using Convert.ToInt32() or int.Parse().

Example: Getting an Integer Input

using System;

class Program {
    static void Main() {
        Console.Write("Enter your age: ");
        int age = Convert.ToInt32(Console.ReadLine()); // Converts input to an integer
        Console.WriteLine("You are " + age + " years old.");
    }
}

Output:

Enter your age: 24
You are 24 years old.

3. Taking Float/Double Input

For decimal numbers, use Convert.ToDouble() or float.Parse().

Example: Getting a Floating-Point Number

using System;

class Program {
    static void Main() {
        Console.Write("Enter your height in meters: ");
        double height = Convert.ToDouble(Console.ReadLine());
        Console.WriteLine("Your height is " + height + " meters.");
    }
}

Output:

Enter your height in meters: 1.75
Your height is 1.75 meters.

4. Taking Multiple Inputs in One Line

Users can enter multiple values in a single line by splitting the input string.

Example: Taking Two Numbers and Adding Them

using System;

class Program {
    static void Main() {
        Console.Write("Enter two numbers separated by space: ");
        string[] inputs = Console.ReadLine().Split(' '); // Splits input at spaces

        int num1 = Convert.ToInt32(inputs[0]);
        int num2 = Convert.ToInt32(inputs[1]);

        Console.WriteLine("Sum: " + (num1 + num2));
    }
}

Output:

Enter two numbers separated by space: 10 20
Sum: 30

5. Handling Boolean Input

Example: Getting a Yes/No Response

using System;

class Program {
    static void Main() {
        Console.Write("Do you like C#? (true/false): ");
        bool likesCSharp = Convert.ToBoolean(Console.ReadLine());
        Console.WriteLine("You answered: " + likesCSharp);
    }
}

Output:

Do you like C#? (true/false): true
You answered: True

6. Handling User Input Errors

If a user enters a non-numeric value when an integer is expected, the program may crash. To prevent this, use exception handling with try-catch.

Example: Handling Incorrect Input

using System;

class Program {
    static void Main() {
        try {
            Console.Write("Enter an integer: ");
            int number = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("You entered: " + number);
        } catch (Exception e) {
            Console.WriteLine("Invalid input! Please enter a valid integer.");
        }
    }
}

Output (if the user enters a non-integer value):

Enter an integer: abc
Invalid input! Please enter a valid integer.

7. User Input in Different Data Types (Table Format)

Data TypeConversion MethodExample
stringConsole.ReadLine()string name = Console.ReadLine();
intConvert.ToInt32(Console.ReadLine())int age = Convert.ToInt32(Console.ReadLine());
doubleConvert.ToDouble(Console.ReadLine())double height = Convert.ToDouble(Console.ReadLine());
floatfloat.Parse(Console.ReadLine())float weight = float.Parse(Console.ReadLine());
boolConvert.ToBoolean(Console.ReadLine())bool isStudent = Convert.ToBoolean(Console.ReadLine());

8. Best Practices for Handling User Input

  • Always validate user input to prevent errors.
  • Use try-catch blocks for error handling.
  • Trim input using .Trim() to remove unnecessary spaces.
  • Use string.Split() to handle multiple values in a single line.

Conclusion

User input is essential for making interactive C# applications. By using Console.ReadLine() and appropriate conversion methods, you can receive input from users and process it efficiently.

For more tutorials, exercises, and quizzes on C# Programming, visit The Coding College and enhance your coding skills! 🚀

Leave a Comment