ASPCode.net logo
  • Home 
  • Blogs 
  • Tags 
Blog
  1. Home
  2. Articles
  3. C# Basics - Input & Casting

C# Basics - Input & Casting

Posted on June 25, 2024  (Last modified on October 11, 2024) • 2 min read • 341 words
C#
 
C#
 
Share via
ASPCode.net
Link copied to clipboard

Video is in Swedish

Title: C# Basics - Input & Casting

Introduction: In this article, we will explore the basics of input and casting in C#. These are fundamental concepts that every programmer should understand to effectively work with data in their programs.

Input in C#: Input refers to the process of getting user input from various sources such as keyboards, mice, or other devices. In C#, there are several ways to get user input, including:

  1. Console.ReadLine(): This method is used to read a line of text entered by the user at the console prompt.
  2. Console.ReadKey(): This method reads a single character from the keyboard and returns its value as an integer.
  3. Console.OpenStandardInput(): This method opens a stream for reading from standard input.

Casting in C#: Casting is the process of converting one data type to another. In C#, casting can be done explicitly or implicitly. Explicit casting involves using the cast keyword, while implicit casting occurs automatically when the compiler determines that it is safe and appropriate.

Explicit Casting: Explicit casting is used when you want to convert a value from one data type to another. For example, if you have an integer variable called “age” and you want to assign its value to a string variable called “name”, you can use explicit casting as follows:

int age = 25;
string name = (string)age; // Explicit Casting

Implicit Casting: Implicit casting occurs when the compiler determines that it is safe and appropriate to convert one data type to another. For example, if you have a double variable called “pi” with a value of 3.14 and you want to assign its value to an integer variable called “roundPi”, the compiler will perform implicit casting as follows:

double pi = 3.14;
int roundPi = (int)pi; // Implicit Casting

Conclusion: In this article, we have learned about input and casting in C#. Input refers to getting user input from various sources, while casting is the process of converting one data type to another. Understanding these concepts is essential for working with data effectively in your programs.

Video  

Swedish

 C# Basics - File IO
C# Basics - String manipulation 
Follow me

I code in Java, C#, Golang, SQL and more

     
© 2024 Systementor AB
ASPCode.net
Code copied to clipboard