C# Type Conversion Scenarios
The comparison of weakly typed conversion in VB.NET and strongly typed conversion in C#—and the different
values obtained in the example I just showed you—demonstrate the importance of getting type conversion right.
It’s your job as a programmer in C# to stage-manage conversions from one type to another.
There are three general ways to convert from one type to another:
Provided that there is no way that the conversion will lose information, C# will implicitly convert for you
without any special syntax. For example, C# will automatically go from integer to long for you (but not from
long to integer).
Implicit conversions must be guaranteed to succeed and not lose information, while explicit conversions are
needed if either:
If you explicitly convert using casting, you are responsible for making sure that the results are what you
anticipate and don’t lead to any unexpected run-time errors. You should anticipate testing your programs with
values appropriate to uncover any possible runtime conversion errors in explicit casts and conversions.
|