Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have foo (object) and foo2 (string) in a C# console application. The Code 2 throws exception while Code 1 works fine.

Can you please explain why it is behaving so (with MSDN reference)?

// Code 1

object foo = null;
string test = Convert.ToString(foo).Substring(0, Convert.ToString(foo).Length >= 5 ? 5 : Convert.ToString(foo).Length);

// Code 2

string foo2 = null;
string test2 = Convert.ToString(foo2).Substring(0, Convert.ToString(foo2).Length >= 5 ? 5 : Convert.ToString(foo2).Length);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
363 views
Welcome To Ask or Share your Answers For Others

1 Answer

From the documentation of Convert.ToString(string):

Return Value
Type: System.String
value is returned unchanged.

So null input will result in a null return value.

From the documentation of Convert.ToString(object):

Return Value
Type: System.String
The string representation of value, or String.Empty if value is null.

(Where "Nothing" means "null" here.)

So null input will result in an empty string (non-null reference) return value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...