String casts in .NET

后端 未结 9 1041
死守一世寂寞
死守一世寂寞 2021-02-15 02:21

Why is there so may ways to convert to a string in .net? The ways I have seen are .ToString, Convert.ToString() and (string). What is the Difference.

9条回答
  •  伪装坚强ぢ
    2021-02-15 03:14

    .ToString() is an instance method which asks the object for its string representation. When the object is null, this will throw a exception.

    (string) is a cast to the string type, which isn't a very good idea in most cases except for simple data types, since it can break (throw an exception) when it's null or an invalid cast

    Convert.ToString() does a bit more checking than a simple cast, giving a more robust alternative to the cast. It will return the empty string when the object is null.

提交回复
热议问题