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 floatother = value; // NOT ALLOWED, a floating-point value does not fit in an integerImplicit conversion table
| Type | Can receive from |
|---|---|
| sbyte | short, int, long, float, double, decimal |
| byte | short, ushort, int, uint, long, ulong, float, double, decimal |
| short | int, long, float, double, decimal |
| ushort | int, uint, long, ulong, float, double, decimal |
| int | long, float, double, decimal |
| uint | long, ulong, float, double, decimal |
| long | float, double, decimal |
| ulong | float, double, decimal |
| char | ushort, int, uint, long, ulong, float, double, decimal |
| float | double |
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
boolindicating 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