Skip to content
C# Studies

Data conversion

Implicit Conversion

  • Conversions that can be performed by simply assigning the value
  • The types involved are compatible
float value = 25.8f;
int other = 25;
value = other; // We can put an int value inside a float
other = value; // NOT ALLOWED, a floating-point value does not fit in an integer

Implicit conversion table

TypeCan receive from
sbyteshort, int, long, float, double, decimal
byteshort, ushort, int, uint, long, ulong, float, double, decimal
shortint, long, float, double, decimal
ushortint, uint, long, ulong, float, double, decimal
intlong, float, double, decimal
uintlong, ulong, float, double, decimal
longfloat, double, decimal
ulongfloat, double, decimal
charushort, int, uint, long, ulong, float, double, decimal
floatdouble

Explicit Conversion

  • Happens when the types are not compatible
  • Done by writing the target type in parentheses before the assignment
int integer = 100;
uint unsignedInteger = (uint)integer;

Using Parse

  • A method available on all primitive types
  • Used to convert a character or string to another type
  • Throws an error if the value is incompatible
int integer = int.Parse("100");

Using Convert

  • Similar to Parse
  • It is a class called Convert that covers all primitive types
  • Can convert many kinds of values, not only strings
  • The target type must always be stated in the call
  • It is more accurate when converting from floating point to integer
int integer = Convert.ToInt32("100");

Using ToString

  • All primitive types have the ToString() method
  • Used to turn a value into a string in our project
int integer = 3;
string value = integer.ToString(); // "3"

Using TryParse()

The TryParse() method does several things at once:

  • It tries to parse a string into the given numeric type.
  • If the conversion succeeds, the converted value is stored in an output parameter, explained in the next section.
  • It returns a bool indicating whether the operation succeeded or failed.

Methods can return a value or return “null”, meaning they return no value. Methods can also return values through out parameters, which are defined like an input parameter but include the out keyword.

string value = "102";
int result = 0;
if (int.TryParse(value, out result)) // out tells where the value goes
{
Console.WriteLine($"Measurement: {result}");
}
else
{
Console.WriteLine("Unable to report the measurement.");
}

Examples:

  • TBD