Coding Fundamentals: Variables

Joe
3 min readMay 2, 2021

The building blocks of programming

What is a variable?

The short answer is that a variable is a container for some type of data. These containers are created by the developer and made for a specific purpose such as tracking a score, storing currency, storing names, and keeping track of items, as a few examples. They allow the creation of these containers for use in the code allowing control over how the variable can be modified during runtime.

All variables contain a few key items so that they can exist within a program. They have a visibility level, which parts of the program can see and modify this variable. This is determined by declaring a variable as

Public: this variable is visible to all classes.

Private: this variable is only visible to the class which it belongs to.

All variables have a data type and have different use cases. Some common data types in C# are

Int: takes up 4 bytes of data and can be any whole number from -2,147,483,648 to 2,147,483,647.

Long: takes up 8 bytes of data and can be any whole number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

Float: take up 4 bytes of data and is a fractional number. Sufficient for storing 6 to 7 decimal digits.

Double: take up 8 bytes of data and is a fractional number. Sufficient for storing 15 decimal digits.

Bool: take up 1 bit of data and stores true or false values.

Char: take up 2 bytes of data and is a single character/letter, surrounded by single quotes

String: take up 2 bytes of data per character and is a sequence of characters, surrounded by double quotes

Next each variable is required to have a name. Names are defined by the developer at the time of creation or through design documentation provided to the developer.

Some examples of variable declaration:

Variable Declaration

Additionally it may be useful to assign the variable a value at the time it is created. This can be accomplished using the = and providing the value. Some examples of variable declaration with assignment:

Variable declaration with assignment

Another handy tip is if you have multiple variables of the same type you can declare them all on the same line.

Declare multiple variables of the same type

There are additional variables which are specific to Unity and variables for other cases but these are the basic variable types and how to put them to use.

Variable Naming Best Practices

Variable names use what is known as camelCase. This is where the first letter is lower case and each subsequent word in the variable is a capital.

variable camelCase examples

Private variables are preceded by an underscore _

private variable examples

--

--