Is it possible to omit the numbers of the formatting arguments of "String.Format" in C #?

3

I was seeing that in Python it is possible to format an unnumbered string the arguments .

Example:

#mensagem = "Meu nome é {0} e minha idade é {1}";

mensagem = "Meu nome é {} e minha idade é {}".format("Wallace", 27)

print(mensagem);

Is there any way in Csharp to set the formatting arguments positionally (ie omitting the number, just like in Python)?

Edit

I need something similar in C #. It would be very useful in a scenario where I need to concatenate strings that need to be formatted, but the numbering of the arguments would need to be dynamic.

Example:

  var parameters = new Dictionary<string, string>() { 
          {"AND [a] = {0} ", TB_A.Text},
          {"AND [b] LIKE '%{1}%' ", TB_B.Text},
          {"AND [c] = '{2}' ", TB_C.Text},
          {"AND [d] = '{3}' ", TB_D.Text}
    };

    foreach (var parameter in parameters)
    {
        // Se o valor for vazio, pula
        // Isso quebra a sequência?
        if (parameter.Value.Length > 0)
        {
            retorno += parameter.Key;
        }
    }

    DataSource.FilterExpression = retorno;

    DataSource.FilterParameters.Clear();

    DataSource.FilterParameters.Add("A", TB_A.Text);
    DataSource.FilterParameters.Add("B", TB_B.Text);
    DataSource.FilterParameters.Add("C", TB_C.Text);
    DataSource.FilterParameters.Add("D", TB_D.Text);

That way currently, when I have {1} , but I do not have {0} , the "formatting" for the {1} value is being ignored. I did some tests and realized that if it obeys a straight positional order (eg 0,1,2,3), it works perfectly.

    
asked by anonymous 06.12.2017 / 15:29

1 answer

2

No, but you can tween :

mensagem = $"Meu nome é {("Wallace")} e minha idade é {27}";

Of course, if it is not a variable or some expression that involves a variable, it does not make sense.

Responding to editing:

public class Program { public static void Main() => System.Console.WriteLine("{0}, {2}, {3}", 1, null, "teste", 23.5); }

See running on .NET Fiddle . And no Coding Ground . Also put it in GitHub for future reference .

I still find this solution awful, should not mount queries like this. Years of gambiarra in PHP gives this: P

Learning to do MCVE is good: P

    
06.12.2017 / 15:31