JavaScript Error

You currently have JavaScript disabled on your web browser.

This website uses JavaScript, and This web page needs JavaScript activated to work correctly.

Please active JavaScript on your web browser and then refresh this web page.

Input



C# provides a very easy-to-use method to quickly get console input from a user, by calling and using the .ReadLine() method.

The following example prompts the user and asks them for a value, which it then stores into a variable, and then outputs the value back to them:

 
// type your username and press enter
Console.WriteLine("Enter username:");

/*
Create a string variable, 
prompt user to get user input, 
and then store users value into the variable
*/
string userName = Console.ReadLine();

// Display the variable value back to the user to show what value they entered
Console.WriteLine("Username is: " + userName);

The full C# code for the above example is as follows:

 
using System;

namespace ThisApp
{
  class MainProgram
  {
    static void Main(string[] args)
    {
      // type your username and press enter
      Console.WriteLine("Enter username:");

      /*
      Create a string variable, 
      prompt user to get user input, 
      and then store users value into the variable
      */
      string userName = Console.ReadLine();

      // Display the variable value back to the user to show what value they entered
      Console.WriteLine("Username is: " + userName);
    }
  }
}

NOTE: The .ReadLine() method always returns a string type variable. Therefore, if you are attempting to get a numerical value from the user, you must CAST the string value into that desired data type (i.e. int) programmatically. Assigning the return value from .ReadLine() directly into an int variable will cause an error. To avoid the error, use the Convert.To methods on the returned value to CAST the value before assigning it to the variable (additional other error checking may also be required).



Final Thoughts

Thank you for reading, I hope you found this blog post (tutorial) educational and helpful.



 
     About   |   Contact Us   |   Privacy   |   Terms & Conditions   |   © 2024 - T&J Divisions, LLC, All Rights Reserved