Let us in the last part talk a bit about how we can
convert between different types in C#.
And you may be thinking hey, Gill,
you said earlier that it is not possible to change a variable type.
Why are you bringing this up again now?
Well, allow me to explain.
Indeed, what you see here on the slide won't work.
This will actually result in a compile time error.
First, we declare an individual variable and we assign it a value of 3,
and in the next line, I assign a string to our variable.
Errors, errors everywhere.
Well, at least, on this line here.
Although we can't change the type of a variable once it is declared,
it is possible to convert its value from one type to another,
and this value will then be assigned to a new variable of the target type.
For this, we'll use conversions, and there are,
in fact, a few options to do this.
We can do an implicit convert, an explicit convert,
also known as a cost, or use a helper.
Let's take a look.
First, let me show you an implicit conversion or an implicit cost.
Say that we create an individual variable and we give it a value.
If you now create another variable of type long and assign a to it,
basically what we're doing is taking the value of A
and passing it to our new variable.
We are indeed working with the value.
Now C# will not complain about this since the data conversion, well, just works.
Longs can contain larger numbers than integers,
and so we're sure that nothing will get lost.
No special syntax is required to do this.
Secondly, let's try doing the same for a double to an integer.
If we try to do this in the same way, well,
the C# compiler would actually complain since now data could actually get lost.
Indeed, a double can contain more than an integer.
Therefore, we need to specify to C# that we actually know what we're doing,
and we need to specify the type you want the value of D to be converted into.
This is done by putting the target type between brackets before D here.
You'll see that not all conversions will basically work this way,
and so they can actually result in a runtime exception causing your application to crash.