format string template with named parameters to literal c#2019 Community Moderator ElectionWhat is the difference between String and string in C#?String output: format or concat in C#?How to escape braces (curly brackets) in a format string in .NETEncrypt and decrypt a string in C#?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?Zebra striping built-in to stringtemplate?Multiline String Literal in C#Pass Method as Parameter using C#C# Split A String By Another StringC# DateTime to “YYYYMMDDHHMMSS” format
Did Amazon pay $0 in taxes last year?
What is the purpose of a disclaimer like "this is not legal advice"?
Is the differential, dp, exact or not?
Should we avoid writing fiction about historical events without extensive research?
Tabular environment - text vertically positions itself by bottom of tikz picture in adjacent cell
Generating a list with duplicate entries
How can I portion out frozen cookie dough?
What the error in writing this equation by latex?
Why does this boat have a landing pad? (SpaceX's GO Searcher) Any plans for propulsive capsule landings?
ESPP--any reason not to go all in?
Who has more? Ireland or Iceland?
How to make sure I'm assertive enough in contact with subordinates?
Why restrict private health insurance?
Averaging over columns while ignoring zero entries
Rationale to prefer local variables over instance variables?
How to install "rounded" brake pads
Why aren't there more Gauls like Obelix?
How spaceships determine each other's mass in space?
What would be the most expensive material to an intergalactic society?
What does it take to become a wilderness skills guide as a business?
What is the best index strategy or query SELECT when performing a search/lookup BETWEEN IP address (IPv4 and IPv6) ranges?
After Brexit, will the EU recognize British passports that are valid for more than ten years?
What does "rhumatis" mean?
Can I frame a new window without adding jack studs?
format string template with named parameters to literal c#
2019 Community Moderator ElectionWhat is the difference between String and string in C#?String output: format or concat in C#?How to escape braces (curly brackets) in a format string in .NETEncrypt and decrypt a string in C#?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?Zebra striping built-in to stringtemplate?Multiline String Literal in C#Pass Method as Parameter using C#C# Split A String By Another StringC# DateTime to “YYYYMMDDHHMMSS” format
I have an application that creates string templates with named variables. This is done in accordance to the logging guide for ASP.NET Core
Now I find myself wanting to deliver these strings through the API itself as well, but this time with all the parameters filled in.
Basicly I'd want to use:
var template = "ID ID not found";
var para = new object[] "value";
String.Format(template, para);
However this gives an invalid input string.
Ofcourse I also cannot guarantee that somebody din't make a string template the 'classic' way with indexes.
var template2 = "ID 0 not found";
Is there a new way of formatting strings that I'm missing or are we supposed to work around this ?
I do not want to rework the existing code base to use numbers or use the $"...para" syntax. As this would lose information when it is being logged.
I'm guessing I could do a regex search and see if there's a '0' or a named parameter, and replace the named with indexes before formatting. But I wanted to know if there are some easier/cleaner ways of doing this.
Update - regex solution:
Bellow is the current work-around I've made using regex
public static class StringUtils
public static string Format(string template, params object[] para)
var match = Regex.Match(template, @"@?w+");
if (!match.Success) return template;
if (int.TryParse(match.Value.Substring(1, match.Value.Length - 2), out int n))
return string.Format(template, para);
else
var list = new List<string>();
var nextStartIndex = 0;
var i = 0;
while (match.Success)
if (match.Index > nextStartIndex)
list.Add(template.Substring(nextStartIndex , match.Index - nextStartIndex) + $"i");
else
list.Add($"i");
nextStartIndex = match.Index + match.Value.Length;
match = match.NextMatch();
i++;
return string.Format(string.Join("",list.ToArray()), para);
c# asp.net-core string.format stringtemplate
|
show 1 more comment
I have an application that creates string templates with named variables. This is done in accordance to the logging guide for ASP.NET Core
Now I find myself wanting to deliver these strings through the API itself as well, but this time with all the parameters filled in.
Basicly I'd want to use:
var template = "ID ID not found";
var para = new object[] "value";
String.Format(template, para);
However this gives an invalid input string.
Ofcourse I also cannot guarantee that somebody din't make a string template the 'classic' way with indexes.
var template2 = "ID 0 not found";
Is there a new way of formatting strings that I'm missing or are we supposed to work around this ?
I do not want to rework the existing code base to use numbers or use the $"...para" syntax. As this would lose information when it is being logged.
I'm guessing I could do a regex search and see if there's a '0' or a named parameter, and replace the named with indexes before formatting. But I wanted to know if there are some easier/cleaner ways of doing this.
Update - regex solution:
Bellow is the current work-around I've made using regex
public static class StringUtils
public static string Format(string template, params object[] para)
var match = Regex.Match(template, @"@?w+");
if (!match.Success) return template;
if (int.TryParse(match.Value.Substring(1, match.Value.Length - 2), out int n))
return string.Format(template, para);
else
var list = new List<string>();
var nextStartIndex = 0;
var i = 0;
while (match.Success)
if (match.Index > nextStartIndex)
list.Add(template.Substring(nextStartIndex , match.Index - nextStartIndex) + $"i");
else
list.Add($"i");
nextStartIndex = match.Index + match.Value.Length;
match = match.NextMatch();
i++;
return string.Format(string.Join("",list.ToArray()), para);
c# asp.net-core string.format stringtemplate
Why don't you tryString.Format(template, string.Join(", ", para));
– Arshad
2 days ago
1
The logging provider used by the ASP.NET Core loggin extensions uses its own formatting code. Some providers actually understand that template, eg Serilog. Some don't. What do you meandeliver these strings through the API itself as wellthough? Whose API?
– Panagiotis Kanavos
2 days ago
I'm making an API and I want to show these messages to the user, that are otherwise just used for logging. Serilog understanding these templates is basicly why I don't want to just rework the code-base to use indexes. I'm using the same string templates and their params for both logging and returning to the user in certain cases.
– Kevin V
2 days ago
1
The approach you're suggesting can lead to runtime errors. If you use "normal" string interpolation then you'll get a compiler error if you have the wrong number of arguments, which is good. If you just have anobject[]then it will compile, but at runtime you could have the wrong number of type of arguments, which is bad. Anything that gets you a compiler error instead of a runtime error is better.
– Scott Hannen
2 days ago
You've added the regex example. Somewhere upstream from where you call this function, you're going to need some code that selects the template. And if your argument is a class with properties, you'll have to convert those properties into a list of parameters (objects.) I'd look for a solution at the point where you're doing that work. Somewhere you've got some arguments you want to format and a decision that tells you what template you need. What does that look like? I'd move it there and avoid a solution that hopes your format string will match your arguments and breaks when it doesn't match.
– Scott Hannen
2 days ago
|
show 1 more comment
I have an application that creates string templates with named variables. This is done in accordance to the logging guide for ASP.NET Core
Now I find myself wanting to deliver these strings through the API itself as well, but this time with all the parameters filled in.
Basicly I'd want to use:
var template = "ID ID not found";
var para = new object[] "value";
String.Format(template, para);
However this gives an invalid input string.
Ofcourse I also cannot guarantee that somebody din't make a string template the 'classic' way with indexes.
var template2 = "ID 0 not found";
Is there a new way of formatting strings that I'm missing or are we supposed to work around this ?
I do not want to rework the existing code base to use numbers or use the $"...para" syntax. As this would lose information when it is being logged.
I'm guessing I could do a regex search and see if there's a '0' or a named parameter, and replace the named with indexes before formatting. But I wanted to know if there are some easier/cleaner ways of doing this.
Update - regex solution:
Bellow is the current work-around I've made using regex
public static class StringUtils
public static string Format(string template, params object[] para)
var match = Regex.Match(template, @"@?w+");
if (!match.Success) return template;
if (int.TryParse(match.Value.Substring(1, match.Value.Length - 2), out int n))
return string.Format(template, para);
else
var list = new List<string>();
var nextStartIndex = 0;
var i = 0;
while (match.Success)
if (match.Index > nextStartIndex)
list.Add(template.Substring(nextStartIndex , match.Index - nextStartIndex) + $"i");
else
list.Add($"i");
nextStartIndex = match.Index + match.Value.Length;
match = match.NextMatch();
i++;
return string.Format(string.Join("",list.ToArray()), para);
c# asp.net-core string.format stringtemplate
I have an application that creates string templates with named variables. This is done in accordance to the logging guide for ASP.NET Core
Now I find myself wanting to deliver these strings through the API itself as well, but this time with all the parameters filled in.
Basicly I'd want to use:
var template = "ID ID not found";
var para = new object[] "value";
String.Format(template, para);
However this gives an invalid input string.
Ofcourse I also cannot guarantee that somebody din't make a string template the 'classic' way with indexes.
var template2 = "ID 0 not found";
Is there a new way of formatting strings that I'm missing or are we supposed to work around this ?
I do not want to rework the existing code base to use numbers or use the $"...para" syntax. As this would lose information when it is being logged.
I'm guessing I could do a regex search and see if there's a '0' or a named parameter, and replace the named with indexes before formatting. But I wanted to know if there are some easier/cleaner ways of doing this.
Update - regex solution:
Bellow is the current work-around I've made using regex
public static class StringUtils
public static string Format(string template, params object[] para)
var match = Regex.Match(template, @"@?w+");
if (!match.Success) return template;
if (int.TryParse(match.Value.Substring(1, match.Value.Length - 2), out int n))
return string.Format(template, para);
else
var list = new List<string>();
var nextStartIndex = 0;
var i = 0;
while (match.Success)
if (match.Index > nextStartIndex)
list.Add(template.Substring(nextStartIndex , match.Index - nextStartIndex) + $"i");
else
list.Add($"i");
nextStartIndex = match.Index + match.Value.Length;
match = match.NextMatch();
i++;
return string.Format(string.Join("",list.ToArray()), para);
c# asp.net-core string.format stringtemplate
c# asp.net-core string.format stringtemplate
edited 2 days ago
Kevin V
asked 2 days ago
Kevin VKevin V
154
154
Why don't you tryString.Format(template, string.Join(", ", para));
– Arshad
2 days ago
1
The logging provider used by the ASP.NET Core loggin extensions uses its own formatting code. Some providers actually understand that template, eg Serilog. Some don't. What do you meandeliver these strings through the API itself as wellthough? Whose API?
– Panagiotis Kanavos
2 days ago
I'm making an API and I want to show these messages to the user, that are otherwise just used for logging. Serilog understanding these templates is basicly why I don't want to just rework the code-base to use indexes. I'm using the same string templates and their params for both logging and returning to the user in certain cases.
– Kevin V
2 days ago
1
The approach you're suggesting can lead to runtime errors. If you use "normal" string interpolation then you'll get a compiler error if you have the wrong number of arguments, which is good. If you just have anobject[]then it will compile, but at runtime you could have the wrong number of type of arguments, which is bad. Anything that gets you a compiler error instead of a runtime error is better.
– Scott Hannen
2 days ago
You've added the regex example. Somewhere upstream from where you call this function, you're going to need some code that selects the template. And if your argument is a class with properties, you'll have to convert those properties into a list of parameters (objects.) I'd look for a solution at the point where you're doing that work. Somewhere you've got some arguments you want to format and a decision that tells you what template you need. What does that look like? I'd move it there and avoid a solution that hopes your format string will match your arguments and breaks when it doesn't match.
– Scott Hannen
2 days ago
|
show 1 more comment
Why don't you tryString.Format(template, string.Join(", ", para));
– Arshad
2 days ago
1
The logging provider used by the ASP.NET Core loggin extensions uses its own formatting code. Some providers actually understand that template, eg Serilog. Some don't. What do you meandeliver these strings through the API itself as wellthough? Whose API?
– Panagiotis Kanavos
2 days ago
I'm making an API and I want to show these messages to the user, that are otherwise just used for logging. Serilog understanding these templates is basicly why I don't want to just rework the code-base to use indexes. I'm using the same string templates and their params for both logging and returning to the user in certain cases.
– Kevin V
2 days ago
1
The approach you're suggesting can lead to runtime errors. If you use "normal" string interpolation then you'll get a compiler error if you have the wrong number of arguments, which is good. If you just have anobject[]then it will compile, but at runtime you could have the wrong number of type of arguments, which is bad. Anything that gets you a compiler error instead of a runtime error is better.
– Scott Hannen
2 days ago
You've added the regex example. Somewhere upstream from where you call this function, you're going to need some code that selects the template. And if your argument is a class with properties, you'll have to convert those properties into a list of parameters (objects.) I'd look for a solution at the point where you're doing that work. Somewhere you've got some arguments you want to format and a decision that tells you what template you need. What does that look like? I'd move it there and avoid a solution that hopes your format string will match your arguments and breaks when it doesn't match.
– Scott Hannen
2 days ago
Why don't you try
String.Format(template, string.Join(", ", para));– Arshad
2 days ago
Why don't you try
String.Format(template, string.Join(", ", para));– Arshad
2 days ago
1
1
The logging provider used by the ASP.NET Core loggin extensions uses its own formatting code. Some providers actually understand that template, eg Serilog. Some don't. What do you mean
deliver these strings through the API itself as well though? Whose API?– Panagiotis Kanavos
2 days ago
The logging provider used by the ASP.NET Core loggin extensions uses its own formatting code. Some providers actually understand that template, eg Serilog. Some don't. What do you mean
deliver these strings through the API itself as well though? Whose API?– Panagiotis Kanavos
2 days ago
I'm making an API and I want to show these messages to the user, that are otherwise just used for logging. Serilog understanding these templates is basicly why I don't want to just rework the code-base to use indexes. I'm using the same string templates and their params for both logging and returning to the user in certain cases.
– Kevin V
2 days ago
I'm making an API and I want to show these messages to the user, that are otherwise just used for logging. Serilog understanding these templates is basicly why I don't want to just rework the code-base to use indexes. I'm using the same string templates and their params for both logging and returning to the user in certain cases.
– Kevin V
2 days ago
1
1
The approach you're suggesting can lead to runtime errors. If you use "normal" string interpolation then you'll get a compiler error if you have the wrong number of arguments, which is good. If you just have an
object[] then it will compile, but at runtime you could have the wrong number of type of arguments, which is bad. Anything that gets you a compiler error instead of a runtime error is better.– Scott Hannen
2 days ago
The approach you're suggesting can lead to runtime errors. If you use "normal" string interpolation then you'll get a compiler error if you have the wrong number of arguments, which is good. If you just have an
object[] then it will compile, but at runtime you could have the wrong number of type of arguments, which is bad. Anything that gets you a compiler error instead of a runtime error is better.– Scott Hannen
2 days ago
You've added the regex example. Somewhere upstream from where you call this function, you're going to need some code that selects the template. And if your argument is a class with properties, you'll have to convert those properties into a list of parameters (objects.) I'd look for a solution at the point where you're doing that work. Somewhere you've got some arguments you want to format and a decision that tells you what template you need. What does that look like? I'd move it there and avoid a solution that hopes your format string will match your arguments and breaks when it doesn't match.
– Scott Hannen
2 days ago
You've added the regex example. Somewhere upstream from where you call this function, you're going to need some code that selects the template. And if your argument is a class with properties, you'll have to convert those properties into a list of parameters (objects.) I'd look for a solution at the point where you're doing that work. Somewhere you've got some arguments you want to format and a decision that tells you what template you need. What does that look like? I'd move it there and avoid a solution that hopes your format string will match your arguments and breaks when it doesn't match.
– Scott Hannen
2 days ago
|
show 1 more comment
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55023248%2fformat-string-template-with-named-parameters-to-literal-c-sharp%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55023248%2fformat-string-template-with-named-parameters-to-literal-c-sharp%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Why don't you try
String.Format(template, string.Join(", ", para));– Arshad
2 days ago
1
The logging provider used by the ASP.NET Core loggin extensions uses its own formatting code. Some providers actually understand that template, eg Serilog. Some don't. What do you mean
deliver these strings through the API itself as wellthough? Whose API?– Panagiotis Kanavos
2 days ago
I'm making an API and I want to show these messages to the user, that are otherwise just used for logging. Serilog understanding these templates is basicly why I don't want to just rework the code-base to use indexes. I'm using the same string templates and their params for both logging and returning to the user in certain cases.
– Kevin V
2 days ago
1
The approach you're suggesting can lead to runtime errors. If you use "normal" string interpolation then you'll get a compiler error if you have the wrong number of arguments, which is good. If you just have an
object[]then it will compile, but at runtime you could have the wrong number of type of arguments, which is bad. Anything that gets you a compiler error instead of a runtime error is better.– Scott Hannen
2 days ago
You've added the regex example. Somewhere upstream from where you call this function, you're going to need some code that selects the template. And if your argument is a class with properties, you'll have to convert those properties into a list of parameters (objects.) I'd look for a solution at the point where you're doing that work. Somewhere you've got some arguments you want to format and a decision that tells you what template you need. What does that look like? I'd move it there and avoid a solution that hopes your format string will match your arguments and breaks when it doesn't match.
– Scott Hannen
2 days ago