Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Type Casting in C#

C# will convert to the appropriate data type at run time automatically if the two types are compatible.

For example,

  1. int iNumber=100;
  2. long aLong1 = (long)iNumber;
  3. long aLong2 = (long)100;


  1. double iNumber;
  2. iNumber = 7;


Casting allows you to make this type conversion explicit, or to force it when it wouldn’t normally happen.

Sometimes the cast is superfluous, since the compiler will automatically promote an int value to a long when necessary.
However, you are allowed to use superfluous casts to make a point or to make your code more clear.


C# - casting safe language:

When you perform a so-called narrowing conversion,
(that is,when you go from a data type that can hold more information to one that doesn’t hold as much)
you have the risk of losing information. Here the compiler forces you to do a cast.
With a widening conversion an explicit cast is not needed because the new type will more than hold the information from the old type so that no information is ever lost.

..