What are and how to use variables in C#

A short text explaining the basics of this every day necessity

Every program you decide to write will use data at some point. I am not talking about databases nor web services. I am talking about plain simple variables.

To put it simple: Variables are nothing more than a named place in the memory where you store something to use later. Think of a box with a name in it and which accepts only certain kind of objects. For example: A box named "balls" which accepts only spherical objects.

In C# we have the following types:

  • Integral: sbyte, byte, short, ushort, int, uint, long, ulong, and char
  • Floating point: float and double
  • Decimal: decimal
  • Boolean: true or false values, as assigned
  • Nullable: Nullable data types

Define your variables

You can define your variables in 2 ways:

  1. [type] [variable_name], [variable_name]; (eg.: string name, surname;)
  2. [type] [variable_name] = [variable_value]; (eg.: string name = "Joe";)

The first one is used when you want to define one or many variables at once, without setting a value. The second alternative can be used when you want to initialize the variable already during its declaration.

Default values

As mentioned above, we can define our variables without initializing it (setting a value). In case we do it, however, we need to pay attention to the default values which each object has. See below:

  • bool: false
  • byte: 0
  • char: '\0'
  • decimal: 0.0M
  • double: 0.0D
  • float: 0.0F
  • int: 0
  • long: 0L
  • sbyte: 0
  • short: 0
  • uint: 0
  • ulong: 0
  • ushort: 0

Notice the letters beside some of those default values. Normally the compiler will require you to specify what kind of value you are assigning to a type. And in order to tell it to the compiler that you want to assign a, for example, double instead of a float you need to add the D in the end of the number.

Sources: MSDN, Tutorials point