Page 197 - CSharp/C#
P. 197

var fooBar = (from DataRow x in fooBarTable.Rows
                   select string.Format("{0}{1}", x["foo"], x["bar"])).ToList();


        Can be re-written as:


         var fooBar = (from DataRow x in fooBarTable.Rows
                   select $"{x["foo"]}{x["bar"]}").ToList();


        Reusable Interpolated Strings




        With string.Format, you can create reusable format strings:


         public const string ErrorFormat = "Exception caught:\r\n{0}";

         // ...

         Logger.Log(string.Format(ErrorFormat, ex));


        Interpolated strings, however, will not compile with placeholders referring to non-existent variables.
        The following will not compile:


         public const string ErrorFormat = $"Exception caught:\r\n{error}";
         // CS0103: The name 'error' does not exist in the current context


        Instead, create a Func<> which consumes variables and returns a String:


         public static Func<Exception, string> FormatError =
             error => $"Exception caught:\r\n{error}";

         // ...

         Logger.Log(FormatError(ex));





        String interpolation and localization



        If you’re localizing your application you may wonder if it is possible to use string interpolation along
        with localization. Indeed, it would be nice to have the possibility to store in resource files Strings
        like:


         "My name is {name} {middlename} {surname}"


        instead of the much less readable:


         "My name is {0} {1} {2}"


        String interpolation process occurs at compile time, unlike formatting string with string.Format



        https://riptutorial.com/                                                                             143
   192   193   194   195   196   197   198   199   200