Variable is dedicated memory location that can store value of specified type. An application can read or write value to memory. Usually variable is of specified type.
By default C# is strongly typed language (there is support for dynamic variables but will get there later). Before a value can be stored, its type must be specified. Syntax reflects that – data type has to be the first. Next comes variable name. Optionally a value can be assigned by using = sign. Here are some examples:
int i = 7; double d; string message = "Welcome"; object obj = new object();
Here you can find a list of Basic (build-in) C# data types. Please note that listed C# types are aliases of predefined .NET Framework types. Here is a table that contains C# type aliases and full .NET Framework type. Please note that you can use both interchangeably – it means that following lines will end up meaning exactly the same for the complier.
int one = 1; System.Int32 one = 1;
Variables vs Consts
Variable is a place in memory that can be changed. Opposite to that is a const – it contain constant value that can’t be changed.
int variableValue = 50; variableValue = 51; // Will work fine const int constValue = 50; constValue = 51; // Will cause compilation error
BTW, Above you can see an example of comment – after // . I’ll do a separate post about C# comments.
Converting data types
There are few types of conversion in C#:
- Implicit conversion – Conversion is done by the complier automatically. No data is lost because of the conversion. Example: converting byte value (range: 0 to 255) to integer value (range: -2 147 483 648 to 2 147 483 647).
byte b = 128; int i = b;
- Explicit conversion (also known as cast ) – Programmer forces the conversion and takes the risk of loosing data.
decimal pi = 3.14; int notPi = (int)pi;
- Other conversions – Sometimes one needs to convert not-compatible types – for example convert string value “123” to integer value 123. For such case there are usually special methods.
string text = "123"; int number = int.Parse(text); // number == 123
Following will compile fine as well, but will fail in runtime (when application is executed).
string text2 = "no number"; int number2 = int.Parse(text2);
You might wonder why compiler won’t detect it – it’s just not so smart :). Compiler is agnostic to content of your variables and doesn’t care what a method will do with it. It’s just another piece of code that syntactically is 100% fine.