String casts in .NET

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

    ToString() is a method of object, and it will always work on a non-null reference, so you'll get something, but whether that something is what you want, is a different story.

    Convert.ToString() will yield the same result in most cases, but isn't as flexible as Object.ToString() as you can't pass custom formatting rules.

    (string) will cast your object to string, and if it isn't a string then you'll get an InvalidCastException().

提交回复
热议问题