Generally, there are four methods for object to string (assuming object OBJ): obj. tostring (), convert. tostring (), (string) OBJ, and OBJ as string. They can all convert object objects to string objects. Let me talk about their similarities and differences and what they should be used in practice.
The first two methods are generally string objects obtained from other objects. The difference between them is only that when the object to be converted is null, if obj is null, obj is called. the tostring method causes nullreferenceexception and calls convert. tostring does not throw an exception and returns a null value.
Forced conversion (string) OBJ requires that the runtime type of OBJ must be string. If not, an exception is thrown.
The AS method is relatively stable. If the runtime type of obj is not string, null is returned without throwing an exception.
Therefore, when we need to get the string expression of an object, we should use tostring and convert. tostring. At this time, you have to select one based on the situation. If you can ensure that your object is not null, then the two are similar. If it is possible to be null, you should use convert. tostring. If you want it to be null and throw an exception, you can select tostring.