DEV Community

Eduardo Julião
Eduardo Julião

Posted on • Updated on

Variables

A variable is a value that can change in your program.

Creating a variable

The structure to create a variable consists of:

<Data Type> <Name> = <Value>;
Enter fullscreen mode Exit fullscreen mode

Data Type

Tells the program what type of variable it is, these can be int, decimal, string, char and others.

Name

A unique name to identify it.

Value

The value of the variable.

Some examples

int i = 10;
decimal d = 5.67;
float f = 7.90;
double d2 = 1.23;

string s = "string";
char c = 'c';

boolean b = true;
byte bt = 64;
Enter fullscreen mode Exit fullscreen mode

Notice that a string is defined by using doble quotes ", while a char is defined by using single quotes '.

Array variables

We can also create a variable type that is the array type, these variables are a list of values of a certain type.

Once an array is created, you can update its values, re-assign, but not extend its size.

Creating an array

<Data Type>[] name = new []{ };

or

<Data Type>[] name = new <Data Type>[<number of entries>];
Enter fullscreen mode Exit fullscreen mode

Arrays are defined by adding [] after the data type, and can be assigned using one of the two forms.

Form 1

<Data Type>[] <Name> = new []{ <value1>, <valiue2> };
Enter fullscreen mode Exit fullscreen mode

In this example, you create an array, that has a length of 3.

int[] arrayOfIntegers = new []{ 1, 2, 3 };
Enter fullscreen mode Exit fullscreen mode

In this form, you don't need to specify the

Form 2

<Data Type>[] <Name> = new <Data Type>[<number of entries>];
Enter fullscreen mode Exit fullscreen mode

In this example, you create an array, that has a length of 4.

int[] arrayOfIntegers = new int[4];
Enter fullscreen mode Exit fullscreen mode

When creating an array in this form, the array will have 4 entries and all set to its default value, which in this case is 0.

Assigning values

You can assign values to an array by using its index, which starts at 0 and ends with its length - 1;

arrayOfIntegers[0] = 1;
arrayOfIntegers[1] = 2;
arrayOfIntegers[2] = 3;
arrayOfIntegers[3] = 4;
Enter fullscreen mode Exit fullscreen mode

Constants

You can create variables that cannot change after being initialized. These types of variables are called constants.

Structure

const <Data Type> <Name> = <Value>;
Enter fullscreen mode Exit fullscreen mode

Example

const int constantIntegerValue = 30;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)