theraot / Theraot

Backporting .NET and more: LINQ expressions in .net 2.0 - nuget Theraot.Core available.
MIT License
162 stars 30 forks source link

[Feature request] Backport FormattableString/FormattableStringFactory #117

Closed ig-sinicyn closed 4 years ago

ig-sinicyn commented 4 years ago

Missing in net 4.5 and earlier. Use case (taken from Meziantou's blog post):

string EscapeCommandLineArgs(FormattableString formattableString)
{
    var args = formattableString.GetArguments()
                   .Select(arg => CommandLineBuilder.WindowsQuotedArgument(string.Format("{0}", arg)))
                   .ToArray();
    return string.Format(formattableString.Format, args);
}

...
var arg1 = "c:\\Program Files\\whoami.exe";
var arg2 = "Gérald Barré";
var commandLine = EscapeCommandLineArgs($"{arg1} {arg2}"); // "c:\Program Files\whoami.exe" "Gérald Barré"
theraot commented 4 years ago

Nuget Version 3.1.1

ig-sinicyn commented 4 years ago

Wow, that's fast. Thanks a lot 👍

ig-sinicyn commented 4 years ago

Oops, System.FormattableString is in wrong namespace. Project

<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFrameworks>net45</TargetFrameworks>
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="Theraot.Core" Version="3.1.1" />
    </ItemGroup>
</Project>

code

using System;
using System.Runtime.CompilerServices;

namespace TestTargeting
{
    class Program
    {
        static void Main(string[] args)
        {
            TestMe($"{123.34}"); // error CS1503: Argument 1: cannot convert from 'string' to 'System.Runtime.CompilerServices.FormattableString'
        }

        public static void TestMe(FormattableString s)
        {
            Console.WriteLine(s.ToString());
        }
    }
}
theraot commented 4 years ago

3.1.2

ig-sinicyn commented 4 years ago

Can confirm it works:)