C
C#ā€¢2y ago
iamramanavenkat

ā” Can't use string interpolation within {}

I'm getting the error when I'm trying to use string interpolation within curly braces{} string uname="abcd"; string pwd ="123"; string fullData= $"{"username": "{uname}","password": "{pwd}"}"; The above code throws an error. I can do this with 2 or more lines. But I need in single line.
7 Replies
Angius
Angiusā€¢2y ago
Double-up the braces you want to be literal
Tvde1
Tvde1ā€¢2y ago
or use C# 11's new feature:
string fullData = $$"""
{
"username": "{{uname}}",
"password": "{{pwd}}"
}
""";
string fullData = $$"""
{
"username": "{{uname}}",
"password": "{{pwd}}"
}
""";
Angius
Angiusā€¢2y ago
Or use JSON serializer mweh
string fullData = JsonSerializer.Serialize(new {
username = uname,
password = pwd
});
string fullData = JsonSerializer.Serialize(new {
username = uname,
password = pwd
});
333fred
333fredā€¢2y ago
Not quite:
string fullData = $$"""
{
"username": "{{uname}}",
"password": "{{pwd}}",
}
""";
string fullData = $$"""
{
"username": "{{uname}}",
"password": "{{pwd}}",
}
""";
Tvde1
Tvde1ā€¢2y ago
darn that's what I did but I undid it later I suppose I forgot there are braces in json
333fred
333fredā€¢2y ago
šŸ˜›
Accord
Accordā€¢2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.