Variales lets us assign some value to a name. Look at this example:
We are declaring a variable,
int meaningOfLife = 42;
, and assigning the value 42 to it. We could have also done:
int meaningOfLife; meaningOfLife = 42;
The difference with the first is that in the first we are also defining the variable at the time we declare it, but here we declare the variable first and define later in the second line.Let's get into detail.
is the type of the variable we're declaring. There are many built-in types in C#:
, etc. You can read more about the basic types here.
int, long, char, byte, string, bool, float, double
Then there is the name of the variable. We named our variable "meaningOfLife". It's a good idea to give variables a meaningful name, not just a ltter like 'a' or "num" as having a variable name without semantic meaning will make code much harder to read. There are few exceptions to this.Then we use the
operator. This is called the assignment operator. It assigns the operand at its right to the variable at the left. We are assigning
. This is a numeric literal. Literals cannot exist on their own, they have to be bound to a variable or, as we will see later, be used in a function call (in the last chapter, the string
was a string literal that wasn't attached to any variable but we used it as a parameter to a function call, which is allowed).
Here we have a
float realMeaningOfLife = 42f; // this is a comment. Comments are not code, they are ignored by the compiler. They just exist as a message to the programmer reading the code. Sometimes it's helpful to write a comment if you think other programmers will not understand well what you are doing. To create a comment, just type // and then your message
variable instead of
. The difference is that float stores a real number, while int stores an integer. The 'f' after the 42 is a literal operator. It tells the compiler to treat the 42 as a real number, not as an integer. By default, all numbers that are alone (that is, without any literal operator), are treated as of type
. Generally, there is a literal operator for each basic built-in numeric type.
This is the first proposed task in this guide. These are meant to help you familiarize and really understand the things you see above. You won't truly understand untill you do it and explore. You will autocorrect yourself, searching on google errors or whatever question you have: google has the asnwer, as I won't reply to any requests via email. I also encourage you to do more than I write here, and to explore things by yourself.