Implicit Conversion: Converting from a smaller data type to a
larger one, which doesn't result in data loss.
Explicit Conversion: Converting from a larger data type to a
smaller one, which may result in data loss. Requires type casting.
Using Convert Class: Utilizing methods from the Convert class for conversion.
TryParse: Safely converting a string to an integer using the int.TryParse() method, which returns a boolean indicating whether the conversion succeeded and outputs the result through an out parameter.
using System;
class Program
{
static void Main(string[] args)
{
// Implicit Conversion (Widening Conversion)
int intValue = 100;
long longValue = intValue; //
Implicitly converting int to long
float floatValue = 3.14f;
double doubleValue = floatValue; // Implicitly converting float to double
// Explicit Conversion (Narrowing Conversion)
double anotherDoubleValue = 123.45;
int anotherIntValue = (int)anotherDoubleValue; // Explicitly converting double to int
// Convert Class
string strValue = "123";
int convertedIntValue =
Convert.ToInt32(strValue); // Using
Convert class for conversion
// Parsing
string numericStr = "456";
int parsedInt = int.Parse(numericStr); //
Using int.Parse() for conversion
// TryParse
string nonNumericStr = "abc";
int result;
bool success = int.TryParse(nonNumericStr, out result); // Using int.TryParse() for safe conversion
// Output
Console.WriteLine($"Implicit Conversion: int to long - {longValue}");
Console.WriteLine($"Implicit Conversion: float to double - {doubleValue}");
Console.WriteLine($"Explicit Conversion: double to int - {anotherIntValue}");
Console.WriteLine($"Using Convert class: string to int - {convertedIntValue}");
Console.WriteLine($"Using Parse: string to int - {parsedInt}");
Console.WriteLine($"Using TryParse: string to int - Success: {success}, Result: {result}");
}
}