Code template implementation with C#
Asked Answered
V

4

3

When I need code template, I can use Python as follows.

templateString = """
%s 
%s
%s
"""

print templateString % ("a","b","c")

How do I implement the equivalent with C#?

I tried

using System;

class DoFile {

    static void Main(string[] args) {
        string templateString = "
        {0}
        {1}
        {2}
        ";
        Console.WriteLine(templateString, "a", "b", "c");
    }
}

But I got

dogen.cs(86,0): error CS1010: Newline in constant
dogen.cs(87,0): error CS1010: Newline in constant
dogen.cs(88,0): error CS1010: Newline in constant

Of course templateString = "{0}\n{1}\n{2}\n"; works, but I need to use multiple line template as the templateString is for generating a part of code, and it's really long.

Vereeniging answered 13/5, 2011 at 18:33 Comment(0)
F
3

you need to place an @ before the first quote

templateString = @"
        {0}
        {1}
        {2}
        ";

make it a verbatim-string-literal

In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-escape-sequence. In particular, simple escape sequences and hexadecimal and Unicode escape sequences *are not processed* in verbatim string literals. A verbatim string literal may span multiple lines.

Fiji answered 13/5, 2011 at 18:35 Comment(0)
O
3

Do this instead (ad @ before the string constant):

class DoFile {

    static void Main(string[] args) {
        string templateString = @"
        {0}
        {1}
        {2}
        ";
        Console.WriteLine(templateString, "a", "b", "c");
    }
}
Overcloud answered 13/5, 2011 at 18:35 Comment(0)
F
3

you need to place an @ before the first quote

templateString = @"
        {0}
        {1}
        {2}
        ";

make it a verbatim-string-literal

In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-escape-sequence. In particular, simple escape sequences and hexadecimal and Unicode escape sequences *are not processed* in verbatim string literals. A verbatim string literal may span multiple lines.

Fiji answered 13/5, 2011 at 18:35 Comment(0)
G
0

U can put @ before the variable name to get multiline strings.

Gourmand answered 13/5, 2011 at 18:37 Comment(0)
D
0

You need to put @ before the quotation marks for the string, this will make it a verbatim string literal and this will still use all of the whitespace you use.

Durable answered 13/5, 2011 at 19:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.