Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

c# - Convert.ToString behaves differently for "NULL object" and "NULL string"

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...