Saturday, October 16, 2021 21:50

Table of contents >> Introduction > Declaring and initializing variables

Declaring and initializing variables

The next topic in our lessons will be declaring and initializing variables. What do those terms mean?

As we already said in a previous lesson, declaring a variable means creating a new variable, by telling the compiler its type and its name. However, our new variable is only created. It does not contain yet any value, or, more correctly, it contains the default value of its type. This is where initialization comes in.

Initializing a variable means declaring a variable and assigning a first, default value to it, using the assign operator of C# (the equal character, “=”). Here is an example of declaring and initializing variables:


Declaring and initializing variables in C#

It is also possible to merge the two terms in a single instruction:


Declaration and assignment of variables in C#

The compiler also allows us to declare multiple variables of the same type in a single instruction:


C# multiple variable declaration

As you could guess, the compiler also allows us to initialize variables declared in a single instruction, but this is a not so popular feature among programmers:


C# multiple variable declaration and initialization

The concepts explained in this lesson are also shown visually as part of the following video:

 

EXERCISES
1. Declare several variables by selecting for each one of them the most appropriate of the types sbyte, byte, short, ushort, int, uint, long and ulong, in order to assign them the following values: 52,130; -115; 4825932; 97; -10000; 20000; 224; 970,700,000; 112; -44; -1,000,000; 1990; 123456789123456789.

Solution


Look up the above variable types value ranges and select the appropriate ones for the given examples.

Tags: , ,

Leave a Reply



Follow the white rabbit