3

I have some code I want to reuse in older versions of c#

List<string> programId = new List<string>(){"1","2","3"}
string.Join(",", Id.Select(x => $"'{x}'"))

How would $ operator be translated to older version of C# ?

6
  • 1
    Backport to older .NET? No need, works out of the box. Commented Jul 18, 2016 at 20:04
  • 1
    @leppie - $ for string interpolation is new to C# 6.0. Commented Jul 18, 2016 at 20:05
  • 1
    @Tim: Even if you select .NET 2 in VS2015 and use it, the C# 6 compiler will compile compatible code. Commented Jul 18, 2016 at 20:11
  • @leppie - Really? So it's truly syntatic sugar then. Commented Jul 18, 2016 at 20:12
  • 1
    @Tim: Mostly, for newer .NET, IFormattable could come into play (but I have not really seen this in practice) Edit: Oops, it could be some other interface I dont recall now :D Commented Jul 18, 2016 at 20:13

2 Answers 2

10
$"'{x}'"

translates to

string.Format("'{0}'", x)

in older versions of C#.

In fact, the String Interpolation version is just compiler syntactic sugar. If you decompile the resulting assembly, you'll find out it all resolves to string.Format calls.

Sign up to request clarification or add additional context in comments.

4 Comments

I do think, ReSharper can forward and backward translate between $ interpolation and string.Format.
It can. At my current job we use CSScript, which doesn't do string interpolation, so I'm always ignoring Resharper's helpful suggestions to convert to string interpolation.
I do love CSScript and use it all the time for all my setup build and deploy scripts! Oleg does an awesome work and support.
@RobertHarvey I dont know much about CSScript, but you could always set the c# language level to a lower one, so It doesnt suggest interpolation
4

How about this?

string.Join(",", Id.Select(x => string.Format("'{0}'", x)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.