C# Training - Variables

Variables

In C#, variables are used to store and manipulate data. Here's how you can declare and use variables in C#:

  1. Variable Declaration:
    - Syntax:
    data_type variable_name;
    - Example:
    int age;
    double height;
    string name;
  2. Variable Initialization:
    - Syntax:
    data_type variable_name = initial_value;
    - Example:
    int age = 25;
    double height = 1.75;
    string name = "John";
  3. Assigning Values to Variables:
    - Once a variable is declared, you can reassign a value to it using the assignment operator (=).
    - Example:
    age = 25;
    height = 1.75;
    name = "John";
  4. Variable Naming Rules: - Variable names can consist of letters, digits, and underscores.
    - They must start with a letter or an underscore.
    - They are case-sensitive (`age` and `Age` are different variables).
    - Choose meaningful names to improve code readability.
  5. Using Variables: - You can use variables in expressions, assignments, and function calls.
    - Example:
    int x = 10;
    int y = 5;
    int sum = x + y; // Using variables in an expression
    string greeting = "Hello, " + name; // Concatenating variables in a string
    Console.WriteLine(sum); // Outputting the value of a variable
  6. Variable Scope:
    - Variables have a scope, which defines where they can be accessed.
    - Local variables: Declared within a method or a block and are only accessible within that scope.
    - Global variables: Declared outside any method or block and can be accessed throughout the program.
  7. Constants:
    - Constants are variables whose values cannot be changed once assigned.
    - Syntax:
    const data_type constant_name = value;
    - Example:
    const double PI = 3.14159;
    const int MAX_VALUE = 100;

Remember to choose appropriate data types for your variables based on the type of data they will store. Understanding variable declaration and usage is crucial for working with data in C#.

Comments