techmore.in

C# - Type Conversion

In C#, type conversion refers to the process of converting a value from one data type to another. C# provides several mechanisms for type conversion, including implicit and explicit conversions, as well as conversion methods and utilities for handling various data types.

Here’s an overview of type conversion in C#:

1. Implicit Conversion

Implicit conversion happens automatically when converting a value from a smaller or less complex type to a larger or more complex type. It does not require explicit casting.

Examples:

csharp
int intValue = 123; double doubleValue = intValue; // Implicit conversion from int to double public class Animal { } public class Dog : Animal { } Animal animal = new Dog(); // Implicit conversion from Dog to Animal

2. Explicit Conversion (Casting)

Explicit conversion requires you to specify the conversion explicitly using a cast operator. This is used when converting between types that are not implicitly convertible.

Examples:

csharp
double doubleValue = 123.45; int intValue = (int)doubleValue; // Explicit conversion from double to int public class Animal { } public class Dog : Animal { } Dog dog = (Dog)animal; // Explicit conversion from Animal to Dog (may throw InvalidCastException)

3. Conversion Methods

C# provides several built-in methods and utilities for type conversion.

Convert Class

The Convert class in the System namespace provides methods for converting different types.

csharp
string stringValue = "123"; int intValue = Convert.ToInt32(stringValue); // Converts string to int double doubleValue = Convert.ToDouble("123.45"); // Converts string to double bool boolValue = Convert.ToBoolean(1); // Converts int to bool

Parse Methods

Many types have static Parse methods for converting strings to other types.

csharp
string stringValue = "123"; int intValue = int.Parse(stringValue); // Parses string to int string doubleStringValue = "123.45"; double doubleValue = double.Parse(doubleStringValue); // Parses string to double

TryParse Methods

TryParse methods are used to safely convert strings to other types, returning a boolean indicating success or failure.

csharp
string stringValue = "123"; if (int.TryParse(stringValue, out int intValue)) { Console.WriteLine("Conversion succeeded: " + intValue); } else { Console.WriteLine("Conversion failed."); } string doubleStringValue = "123.45"; if (double.TryParse(doubleStringValue, out double doubleValue)) { Console.WriteLine("Conversion succeeded: " + doubleValue); } else { Console.WriteLine("Conversion failed."); }

4. Custom Conversions

You can define custom conversion methods in your own classes by implementing implicit and explicit operators.

Example:

csharp
public class Celsius { public double Temperature { get; set; } public Celsius(double temperature) { Temperature = temperature; } // Implicit conversion from Celsius to Fahrenheit public static implicit operator Fahrenheit(Celsius celsius) { return new Fahrenheit(celsius.Temperature * 9 / 5 + 32); } // Explicit conversion from Fahrenheit to Celsius public static explicit operator Celsius(Fahrenheit fahrenheit) { return new Celsius((fahrenheit.Temperature - 32) * 5 / 9); } } public class Fahrenheit { public double Temperature { get; set; } public Fahrenheit(double temperature) { Temperature = temperature; } } class Program { static void Main() { Celsius celsius = new Celsius(25); Fahrenheit fahrenheit = celsius; // Implicit conversion Console.WriteLine("Temperature in Fahrenheit: " + fahrenheit.Temperature); celsius = (Celsius)fahrenheit; // Explicit conversion Console.WriteLine("Temperature in Celsius: " + celsius.Temperature); } }

5. Boxing and Unboxing

Boxing and unboxing are used to convert between value types (such as int, double) and object.

Boxing

Boxing is the process of converting a value type to an object type.

csharp
int intValue = 123; object objValue = intValue; // Boxing

Unboxing

Unboxing is the process of converting an object type back to a value type.

csharp
object objValue = 123; int intValue = (int)objValue; // Unboxing

6. Type Casting in Collections

When dealing with collections, you might need to cast elements to a specific type.

Example:

csharp
List<object> objects = new List<object> { "Hello", 123, 45.67 }; foreach (object obj in objects) { if (obj is string str) { Console.WriteLine($"String value: {str}"); } else if (obj is int intValue) { Console.WriteLine($"Integer value: {intValue}"); } else if (obj is double doubleValue) { Console.WriteLine($"Double value: {doubleValue}"); } }

Summary

In C#, type conversion is an essential feature that allows you to convert between different data types. Implicit conversions occur automatically, while explicit conversions require explicit casting. The Convert class, Parse, and TryParse methods provide additional tools for converting values. Custom conversions can be defined using implicit and explicit operators, and boxing and unboxing are used for converting between value types and object. Understanding these concepts helps manage and manipulate different data types effectively in C#.