Start Coding

Topics

C# Type Conversion

Type conversion is a fundamental concept in C# programming. It allows you to convert values from one data type to another, enabling flexibility and interoperability between different parts of your code.

Implicit Conversion

Implicit conversion occurs automatically when there's no risk of data loss. The compiler handles these conversions without requiring explicit syntax.


int myInt = 10;
long myLong = myInt; // Implicit conversion from int to long
    

Explicit Conversion (Casting)

When there's a risk of data loss or when converting between incompatible types, explicit conversion is necessary. This is done using casting syntax.


double myDouble = 3.14;
int myInt = (int)myDouble; // Explicit conversion from double to int
    

Convert Class

The Convert class provides methods for converting between various data types. It's particularly useful for string conversions.


string myString = "42";
int myInt = Convert.ToInt32(myString);
    

Parse Method

Many value types in C# have a Parse method that converts strings to that type.


string myString = "3.14";
double myDouble = double.Parse(myString);
    

TryParse Method

For safer conversions, use the TryParse method. It returns a boolean indicating success and outputs the converted value if successful.


string input = "42";
if (int.TryParse(input, out int result))
{
    Console.WriteLine($"Conversion successful: {result}");
}
else
{
    Console.WriteLine("Conversion failed");
}
    

User-Defined Conversions

C# allows you to define custom conversion operators for your own types. This is useful when working with complex data structures or domain-specific types.


public struct Celsius
{
    public double Temperature { get; }

    public Celsius(double celsius)
    {
        Temperature = celsius;
    }

    public static explicit operator Fahrenheit(Celsius celsius)
    {
        return new Fahrenheit(celsius.Temperature * 9 / 5 + 32);
    }
}
    

Best Practices

  • Always check for potential data loss when performing conversions.
  • Use TryParse methods for user input to handle invalid conversions gracefully.
  • Be aware of the performance implications of frequent type conversions, especially in loops.
  • When working with custom types, consider implementing both implicit and explicit conversions where appropriate.

Understanding type conversion is crucial for writing robust C# code. It's closely related to C# Data Types and often used in conjunction with C# Operators. For more advanced scenarios, you might want to explore C# Generics to create more flexible and type-safe code.