Home >Backend Development >C++ >How Can I Cast or Convert Objects to Generic Types in C#?
Casting Variables Using Generic Type Variables
In C# programming, it is possible to cast variables of type object to variables of a generic type T, where T is defined in a Type variable. Here's how it works:
The generic method CastObject
public T CastObject<T>(object input) { return (T) input; }
The generic method ConvertObject
public T ConvertObject<T>(object input) { return (T) Convert.ChangeType(input, typeof(T)); }
For example, given an object value1 with a decimal value, casting it to an int using the ConvertObject method will result in an integer value:
Type intType = typeof(Int32); object value1 = 1000.1; int value2 = Convert.ChangeType(value1, intType); // value2 will be 1000
It's important to note that casting and conversion might lead to runtime exceptions if the target type is not compatible with the source type. It's always crucial to handle type-casting operations carefully and ensure the expected outcome.
The above is the detailed content of How Can I Cast or Convert Objects to Generic Types in C#?. For more information, please follow other related articles on the PHP Chinese website!