C# Variables

What are variables in C#?

There is always something called a variable in any programming language, not just C#. In this tutorial, I will briefly describe such variables.

What is a variable?

A variable is a box for temporarily storing a value.

When you were a student, you may have learned that x = 1, y = 2, z =3. 

This is exactly what a variable is.

For example:

x = 3;

x = x + 1;

Isn't it strange that x = x + 1? You may be thinking, "What's wrong with that?

In programming, "= (equal)" means to assign to the left-hand side, and most programming languages, not just C#, are written in the same way.

Since it means to assign to the left-hand side, x = x + 1, the content of variable x is 4.

A variable, in this case, is a number, but variables can also contain letters and a variety of other things.

The data can be stored in the memory.

These are called variables.

Declaring Variables

There is a simple rule for declaring the variables mentioned earlier in C#.

[Type] [Variable name];

In C#, you can declare a variable by specifying the type followed by the variable name.

Example:

 int number;
 string name;

You can also write the initial value, setting it on a single line like this:

[Type] [Variable name] = value;

Example:

int number = 10;
string name = "James";

Sample code:

  1. using System;
  2. namespace CSharp_Variable_Sample
  3. {
  4. public class Program
  5. {
  6. public static void Main(string[] args)
  7. {
  8. //Declare
  9. int number;
  10. string name;
  11. //
  12. int number2 = 100;
  13. string name2 = "James";
  14. //Print
  15. Console.WriteLine("Number: {0}", number2);
  16. Console.WriteLine("Name: {0}", name2);
  17. }
  18. }
  19. }

Output

Number: 100
Name: James

C# tutorials


See also:
C# List Contains with Examples
C# typeof with Examples
C# TryParse (int, double, float) with Examples
C# Data Types
C# IndexOf() – List, Array, ArrayList, String