Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert.ChangeType Method in C#
The Convert.ChangeType() method in C# converts a value to a specified type. It returns an object of the target type whose value is equivalent to the original object. This method is particularly useful when you need to perform type conversions at runtime or when working with generic code.
Syntax
Following is the syntax for the Convert.ChangeType() method −
public static object ChangeType(object value, Type conversionType) public static object ChangeType(object value, TypeCode typeCode)
Parameters
- value − The object to convert.
-
conversionType − The target
Typeto convert to. -
typeCode − The
TypeCoderepresenting the target type.
Return Value
Returns an object of the specified type with a value equivalent to the original object. The returned object must be cast to the appropriate type before use.
Using Convert.ChangeType with TypeCode
Example
using System;
public class Demo {
public static void Main() {
double val = -3.456;
int num = (int)Convert.ChangeType(val, TypeCode.Int32);
Console.WriteLine("{0} converted to an Int32: {1}", val, num);
string str = "123.45";
double convertedDouble = (double)Convert.ChangeType(str, TypeCode.Double);
Console.WriteLine("{0} converted to Double: {1}", str, convertedDouble);
}
}
The output of the above code is −
-3.456 converted to an Int32: -3 123.45 converted to Double: 123.45
Using Convert.ChangeType with Type
Example
using System;
public class TypeConversionDemo {
public static void Main() {
object[] values = { 42, "100", 3.14, true };
Type[] targetTypes = { typeof(string), typeof(int), typeof(int), typeof(int) };
for (int i = 0; i < values.Length; i++) {
try {
object converted = Convert.ChangeType(values[i], targetTypes[i]);
Console.WriteLine("Original: {0} ({1}) -> Converted: {2} ({3})",
values[i], values[i].GetType().Name, converted, targetTypes[i].Name);
}
catch (Exception ex) {
Console.WriteLine("Conversion failed: {0}", ex.Message);
}
}
}
}
The output of the above code is −
Original: 42 (Int32) -> Converted: 42 (String) Original: 100 (String) -> Converted: 100 (Int32) Original: 3.14 (Double) -> Converted: 3 (Int32) Original: True (Boolean) -> Converted: 1 (Int32)
Exception Handling
The Convert.ChangeType() method can throw various exceptions. It's important to handle them appropriately −
Example
using System;
public class SafeConversionDemo {
public static void Main() {
string invalidNumber = "NotANumber";
try {
int result = (int)Convert.ChangeType(invalidNumber, typeof(int));
Console.WriteLine("Converted: " + result);
}
catch (FormatException) {
Console.WriteLine("FormatException: Cannot convert '{0}' to integer", invalidNumber);
}
catch (InvalidCastException ex) {
Console.WriteLine("InvalidCastException: {0}", ex.Message);
}
}
}
The output of the above code is −
FormatException: Cannot convert 'NotANumber' to integer
Common Use Cases
| Scenario | Example |
|---|---|
| Generic type conversion | Converting unknown object types at runtime |
| String to numeric conversion | Converting user input strings to numbers |
| Cross-type operations | Converting between compatible value types |
| Data processing | Converting data from files or databases |
Conclusion
The Convert.ChangeType() method provides a flexible way to convert objects between compatible types at runtime. It's particularly useful for generic programming and dynamic type conversion, but always use proper exception handling to manage invalid conversions gracefully.
