Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 views
in Technique[技术] by (71.8m points)

c# - How do I interpolate strings?

I want to do the following in C# (coming from a Python background):

strVar = "stack"
mystr  = "This is %soverflow" % (strVar)

How do I replace the token inside the string with the value outside of it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This has been added as of C# 6.0 (Visual Studio 2015+).

Example:

var planetName = "Bob";
var myName = "Ford"; 
var formattedStr = $"Hello planet {planetName}, my name is {myName}!";
// formattedStr should be "Hello planet Bob, my name is Ford!"

This is syntactic sugar for:

var formattedStr = String.Format("Hello planet {0}, my name is {1}!", planetName, myName);

Additional Resources:

String Interpolation for C# (v2) Discussion

C# 6.0 Language Preview


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...