What Are Variables?
Essentially we can think of variables in computer memory as boxes sitting on a shelf. With boxes we can put things in and take them out again, or we can just look inside a box and see if anything is there. The same goes for variables; we place data in them and can take it out or look at it, as required.
Although all data in a computer is effectively the same thing (a series of zeros and ones), variables come in different flavors, known as types. Again, using our box analogy we can imagine that our boxes come in different shapes and sizes, and some things will only fit in certain boxes. The reasoning behind this type system is that different types of data may require different methods of manipulation, and by restricting variables into individual types we can avoid getting mixed up. It wouldn't, for example, make much sense to treat the series of zeros and ones that make up a digital picture as an audio file.
In order to use variables, we have to declare them. This means we have to assign them a name and a type. Once we have declared variables we can use them as storage units for the type of data that we have declared them to hold.
The C# syntax for declaring variables simply involves specifying the type and variable name as follows:
Code: <type> <name>;
If we try to use a variable that hasn't been declared, then our code won't compile, but in this case the compiler will tell us exactly what the problem was, so this really isn't a disastrous error. In addition, trying to use a variable without assigning it a value will also cause an error, but again, the compiler will detect this.
So, what are the types we can use?
Well, in actual fact, there are an infinite number of types that we can use. The reason for this is that we can define our own types to hold whatever convoluted data we like. More on this in future blogs...