The type conversion in the c#
C# offers a variety of object type conversion methods: direct conversion, "AS" operator and Tostring () method.
Direct conversion
Direct conversion, grammar is (string) O, and try to convert the object to a specified type. If the conversion is successful, the new value will be assigned to the variable; otherwise, the INVALIDCASTTEXCEPTION will be thrown out. This method is usually used for developers to confirm the conversion scenarios of object types.
"AS" operator
AS "operator, writing o as string, try to convert the object into a specified type. Unlike direct conversion, if the conversion fails, it returns NULL. This computing symbol is often used for developers uncertain object types or expected NULL values.
Tostring () method is not a type conversion operation, but the string representation of the object that can be used to obtain the object. This method is usually used to indicate the form of the object string to represent the form, regardless of its type.
Suggestion
For most conversion, direct conversion is the first choice, because it has the least ambiguity and higher performance. However, when the NULL value is expected to be eliminated, the "AS" operator is more suitable. The Tostring () method should be retained in the scenario that requires the form of the object string, regardless of its type.
The above is the detailed content of How to Choose the Best Casting Method in C#?. For more information, please follow other related articles on the PHP Chinese website!