Why is there no exception when adding null to a string?

断了今生、忘了曾经 提交于 2020-01-14 07:19:10

问题


Why doesnt this throw an exception dont understand, obj is null

object obj = null;
Console.WriteLine("Hello World " + obj);

回答1:


This compiles to

Console.WriteLine(String.Concat("Hello World ", obj));

The String.Concat method ignores null parameters.

It's defined like this: (From the .Net reference source)

    public static String Concat(Object arg0, Object arg1) {
        if (arg0==null) {
            arg0 = String.Empty; 
        }

        if (arg1==null) { 
            arg1 = String.Empty;
        } 
        return Concat(arg0.ToString(), arg1.ToString());
    }

I don't know why it doesn't simply return arg1.ToString() if arg0==null.

The String.Concat(string, string) method is defined like this:

    public static String Concat(String str0, String str1) { 
        if (IsNullOrEmpty(str0)) { 
            if (IsNullOrEmpty(str1)) {
                return String.Empty; 
            }
            return str1;
        }

        if (IsNullOrEmpty(str1)) {
            return str0; 
        } 

        int str0Length = str0.Length; 

        String result = FastAllocateString(str0Length + str1.Length);

        FillStringChecked(result, 0,        str0); 
        FillStringChecked(result, str0Length, str1);

        return result; 
    }



回答2:


Passing a null parameter to a method is not necessarily going to throw an exception; that's up to the implementation of the method (and in that case you'd probably see an ArgumentNullException).

Attempting to access a member* of a null object** is what will always throw a NullReferenceException, guaranteed***.

So...

May or may not throw an exception

object obj = null;
SomeMethod(obj); // passing as parameter

Will definitely throw an exception

object obj = null;
int hashCode = obj.GetHashCode(); // calling instance method

In the case of the code in question, the parameter you are passing to Console.WriteLine is actually the result of a compiled call to string.Concat, which allows null values to be passed as parameters and essentially ignores them -- as SLaks already pointed out.


*Extension methods are a different matter; they can be called on "null" parameters; but since these only present the illusion of acting like instance methods, this rule does not apply to them. In fact, extension methods are after all just static methods. If you call one "on" a null value, you are effectively passing null as a parameter.

**Here I am not including Nullable<T> values with HasValue == false; though these might conveniently be treated as null in many cases, this is just for syntactical convenience: they are no more null than any other value type can ever be null.

***I'm talking about C# here. As SLaks points out in a comment, this is not a rule of the CLI itself. But all instance method calls in C# are compiled to callvirt instructions in IL, which will throw an exception if the instance is null.




回答3:


Because that would be annoying. For most pruposes there is no semantic difference between an empty and a null string.




回答4:


If you have an issue where this might occur in a real application, you could always check for null before displaying the text. Then, you could display an alternate text, or nothing.




回答5:


Because they implemented String.IsNullOrEmpty and left it to us to figure out how to use it.



来源:https://stackoverflow.com/questions/3312504/why-is-there-no-exception-when-adding-null-to-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!