SoFunction
Updated on 2025-03-07

A brief discussion on the difference between ToString in C#

A brief discussion on the difference between ToString() and() methods

1. General usage description

ToString() is an extension method of Object, so there are all ToString() methods; and (param) (where the data type of the param parameter can be various basic data types, or it can be a bool or object class object.

2. The difference between ToString() and ()

Generally, both methods can be general, but when a null value may appear in the returned data type, if the ToString method is called, a NullReferenceException will be returned. Unless you want to catch this exception and then process it, you should consider using the() method in this case, because (null) will not throw an exception but will return an empty string.
The main difference is as shown above. Since ToString() is an extension method, it extends from Object, so it turns to null and reports an exception. And () returns an empty string.

However, (), the effect is not too great, because:

static void Main(string[] args)
    {
      string str1 = "";
      ((str1) == null); //false
      ((str1) == "");  //true

      string str2 = null;
      ((str2) == null); //true
      ((str2) == "");  //false

      ();
    }

After null, it is still null, ""After null, it is still "".

Therefore, it is quite convenient to cooperate with (()).

    (((str1)));  //true
    (((str1)));  //true

In addition, if it is compared with a certain string, it is very convenient to use(), for example

if((str) == "123")
{

}

3. The conversion from object to string

There are roughly four ways from object to string, including explicit conversion and the use of as keywords: (), (), (string)obj, obj as string. They can all convert object objects into string objects.

The first two methods usually obtain string objects from other objects. The difference between them is mainly reflected in:

ToString() : If obj is null, calling the () method will cause a NullReferenceException exception.

(): If obj is null, calling () will return null

(string): Use cast (string)obj to require that the runtime type of obj must be string. If not, an exception will be thrown.

as: Using the as method will be relatively stable. When the runtime type of obj is not string, it will return null without throwing an exception.

So when we usually need to get the string expression of an object, we should use ToString() and (). At this time, you have to choose one according to the situation. If you can ensure that your object is not null, then the two are almost the same. If it is possible to be null, you should use (). If you want it to throw an exception when null, then of course you can choose ToString().

The ToString() method is so convenient that I think that in this method, it is usually determined whether it is null before turning.

The above is the entire content of this article, I hope it will be helpful to everyone!