Types of Variables

In C#, variables can be of different types depending on the kind of data they hold. Each type ensures that the variable can only store specific types of data, ensuring the correct operations and memory allocation for that data.

Key Concepts

  • int: Used for storing whole numbers (e.g., 25).
  • string: Used for storing text or sequences of characters (e.g., "Hello").
  • double: Used for floating-point numbers (e.g., 3.14).
  • Other types include bool, float, and char, each serving different purposes.

Example of Declaring Different Types of Variables

Code Example

// Declare variables of different types
int age = 30;
string name = "Alice";
double height = 5.9;

// Output the values to the console
Console.WriteLine($"Name: {name}, Age: {age}, Height: {height}");

Output:

Name: Alice, Age: 30, Height: 5.9

Code Explanation: Three variables are declared: age is an int (integer), name is a string (text), and height is a double (floating-point number). Each variable is initialized with appropriate values and printed using the Console.WriteLine() method.

Output Explanation: The values for age, name, and height are printed as Name: Alice, Age: 30, Height: 5.9.