C# Variables

In C#, a variable is a named storage location in computer memory where data can be stored and manipulated during the execution of a program. Variables are used to hold values of different data types such as integers, floating-point numbers, characters, strings, and custom objects.

Variables in C# have the following characteristics:

  • Data Type: Every variable in C# has a data type that defines the type of data it can hold. Data types include primitive types like int, float, double, char, bool, etc., as well as user-defined types like classes and structures.

  • Name: A variable is identified by its name, which must be a valid identifier according to C# naming rules. Variable names should be descriptive and follow camelCase or PascalCase conventions.

  • Value: Variables can hold a single value at a time. The value stored in a variable can be changed during the execution of the program.

  • Scope: Variables have a scope that defines the region of code where they are accessible. C# supports local variables (defined within a method or block), instance variables (associated with an instance of a class), and static variables (associated with a class).
    Question - What is the difference between var and let in C#?

  • Lifetime: The lifetime of a variable refers to the duration for which the variable exists in memory. Local variables are created when the block containing their declaration is entered and destroyed when the block is exited. Instance variables exist as long as the instance of the class exists, while static variables exist for the entire duration of the program execution.

Here's an example of variable declaration and initialization in C#:

using System;

namespace VariablesExample
{
    class Variable
    {
         static void Main(string[] args)
        {
            int age; // Declaration of a variable 'age' of type integer
            age = 25; // Initialization of 'age' with the value 25

             string name = "John"; // Declaration and initialization of a string variable 'name'
        }
    }
}

In this example, age is an integer variable, and name is a string variable. They hold values 25 and "John" respectively.

We will discuss more about data types(int, string and many more) in next chapter.