How do I interpolate strings?

前端 未结 15 772
感情败类
感情败类 2020-11-27 05:38

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

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

How do I

15条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 06:03

    Basic example:

            var name = "Vikas";
            Console.WriteLine($"My name is {name}");
    

    Adding Special characters:

    string name = "John";
    Console.WriteLine($"Hello, \"are you {name}?\", but not the terminator movie one :-{{");
    //output-Hello, "are you John?", but not the terminator movie one :-{
    

    Not just replacing token with value, You can do a lot more with string interpolation in C#

    Evaluating Expression

    Console.WriteLine($"The greater one is: { Math.Max(10, 20) }");
    //output - The greater one is: 20
    

    Method call

        static void Main(string[] args)
        {
            Console.WriteLine($"The 5*5  is {MultipleByItSelf(5)}");
        }
      
        static int MultipleByItSelf(int num)
        {           
            return num * num;
        }
    

    Source: String Interpolation in C# with examples

提交回复
热议问题