String casts in .NET

后端 未结 9 1066
死守一世寂寞
死守一世寂寞 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:20

    Think.

    ToString is a virtual method, and each type can implement it however it wants. Also System.Object provides default implementations so that it always succeeds. Convert.ToString works only with nulls as well and allows you to use IFormat provier as noted in the comment.

    Casting to string requires object to implement casting operator. Again, types can implement it however they like, but most types do not, so you may get an exception here.

    Use .ToString as your best option.

提交回复
热议问题