Would you like to store values? Think of a Variable :)
Well, programming in essence deals with just two entities. Value and ways to use that value. That's it! The whole idea is to get the value in its most secure place and then have a method to use when there is a need.
A variable is an entity that handles storage.
None of us would have not stored anything in real life. Starting from the most mundane task of every morning, we store toothbrushes, shampoo, clothes, shoes, food, medicines, money, office files, etc. by putting them in their most suitable places.
Similarly, we put digital items in their most suitable variables. Another similarity is that as we change our daily items but not the storage (Unless it is broken), we could also change the value in the variables and still use them.
That's why they are called “variables”, they can vary :)
How many types of variables are there? At the base level, we have value types and reference types. The formers include whole numbers, decimal point numbers, double, character, boolean. The latter has strings, arrays, and other user-defined data types.
You would store your data values in the respective variable by following a common syntax.
- First, declare the type of your variable. (Or let c# do it for you.)
- Second, give a name of your choice to it. (c# can not do it for you.)
- Third, initialize it by putting your value in it. (You can do it later also.)
int playerHealth= 10; || var playerHealth = 10; (Both are fine :) )
char myFirstLetter = “S”; || var myFirstLetter = “S”; (Both are fine :) )
- Alternatively, if you would like the variable to be on standby and use it at a later stage, you could declare it first and assign the value afterward.
int playerHealth; || var playerHealth;
playerHealth = 10;
Now, there are two other dimensions to remember for variables.
- First, you can not change the type variable once declared. So, if you had tagged it as a container for “int” type data, you’d not be able to store any other type of data in it except a whole number.
- Second, these value-type variables have a size constraint. For example, if you had chosen an “int” type of variable, there is a strict limit to a min or max number that’d be stored in it. Anything larger or smaller than the limit would result in overflow/underflow. Below is the standard for sizes.
Please check out the link here to see more on the size constraints by Microsoft.
- However, these days you would be mostly okay using int, float, and double as your variable’s data type while dealing with numbers.
When we speak of reference types, we are talking about what is being stored in the variable. Instead of a value getting stored in it, a reference data type variable will store a reference to a memory location.
- The reference types and memory locations better are discussed in a separate article :)
Thank you very much