Utilizor
Contact Us

C# Variables

Storing data in variables.

C# Variables

Variables are containers for storing data values.

In C#, there are different types of variables (defined with different keywords), for example:

  • int - stores integers (whole numbers), without decimals, like 123 or -123
  • double - stores floating point numbers, with decimals, like 19.99 or -19.99
  • char - stores single characters, like 'a' or 'B'. Char values are surrounded by single quotes
  • string - stores text, like "Hello World". String values are surrounded by double quotes
  • bool - stores values with two states: true or false

Declaring (Creating) Variables

To create a variable, you must specify the type and assign it a value:

type variableName = value;

Constants

If you don't want others (or yourself) to overwrite existing values, you can add the const keyword in front of the variable type.

This will declare the variable as "constant", which means unchangeable and read-only.

Examples

String Variable

Storing and printing a name.

using System;

class Program
{
  static void Main(string[] args)
  {
    string name = "John";
    Console.WriteLine(name);
  }
}

Integer Variable

Storing and printing a number.

using System;

class Program
{
  static void Main(string[] args)
  {
    int myNum = 15;
    Console.WriteLine(myNum);
  }
}

Change Variable Value

Overwriting a variable's value.

using System;

class Program
{
  static void Main(string[] args)
  {
    int myNum = 15;
    myNum = 20; // myNum is now 20
    Console.WriteLine(myNum);
  }
}

Combine Variables

Concatenating strings.

using System;

class Program
{
  static void Main(string[] args)
  {
    string firstName = "John ";
    string lastName = "Doe";
    string fullName = firstName + lastName;
    Console.WriteLine(fullName);
  }
}

Constant Variable

Using the const keyword.

using System;

class Program
{
    static void Main()
    {
        const int myNum = 15;
        // myNum = 20; // error: cannot assign to 'myNum' because it is readonly
        Console.WriteLine(myNum);
    }
}