Cannot use String.Empty as a default value for an optional parameter

前端 未结 8 1609
生来不讨喜
生来不讨喜 2020-12-04 14:47

I am reading Effective C# by Bill Wagner. In Item 14 - Minimize Duplicate Initialization Logic, he shows the following example of using the new opt

相关标签:
8条回答
  • 2020-12-04 15:52

    As of the C# 2.0 compiler, there is very little point to String.Empty anyway, and in fact in many cases it's a pessimisation, since the compiler can inline some references to "" but can't do the same with String.Empty.

    In C# 1.1 it was useful to avoid creating lots of independent objects all containing the empty string, but those days are gone. "" works just fine.

    0 讨论(0)
  • 2020-12-04 15:53

    There's nothing to stop you from defining your own constant for the empty string if you really want to use it as an optional parameter value:

    const string String_Empty = "";
    
    public static void PrintString(string s = String_Empty)
    {
        Console.WriteLine(s);
    }
    

    [As an aside, one reason to prefer String.Empty over "" in general, that hasn't been mentioned in the other answers, is that there are various Unicode characters (zero-width joiners, etc.) that are effectively invisible to the naked eye. So something that looks like "" isn't necessarily the empty string, whereas with String.Empty you know exactly what you're using. I recognise this isn't a common source of bugs, but it is possible.]

    0 讨论(0)
提交回复
热议问题