-2

Here is the code

class Coords {

 public int x, y;

 public Coords() {
  x = 0;
  y = 0;
 }

 public override string ToString() {
  return $ "({x},{y})";
  }
}

Can you explain what is $ doing there? Also, I tried to run it but it showed a compilation error.

Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
  • return $"({x},{y})"; – Prashant Pimpale Jan 05 '19 at 05:39
  • check for syntax error --> `,` – Prashant Pimpale Jan 05 '19 at 05:41
  • 1
    [$ - string interpolation - C# Reference | Microsoft Docs](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated) – Mohamed Elrashid Jan 05 '19 at 05:44
  • Regarding the compilation error: We need to know your version of Visual Studio and project setting. When you have old version of Visual Studio (2013 and before), or you have set old C# language (C# 5 or less), this code will not compile. To change C# version setting see [this link](https://dailydotnettips.com/choosing-the-c-language-latest-version-minor-release-in-visual-studio-2017/). – Julo Jan 05 '19 at 05:50

5 Answers5

1

For your first question.

Can you explain what is $ doing there?

Ans:

The $ special character identifies a string literal as an interpolated string. An interpolated string is a string literal that might contain interpolated expressions. When an interpolated string is resolved to a result string, items with interpolated expressions are replaced by the string representations of the expression results. This feature is available in C# 6 and later versions of the language.

You can read more about interpolation here

For your second question.

I tried to run it but it showed a compilation error.

Ans:

Remove the space from here

return $ "({x},{y})"
        ^

So it becomes

return $"({x},{y})";

If you are using c# version below than 6 then this will be same as interpolation.

return string.Format("({0},{1})", x, y);
er-sho
  • 9,581
  • 2
  • 13
  • 26
0

That is named string interpolation

public override string ToString()
{
    return $"({x},{y})";
}

This is the same

public override string ToString()
{
    return "(" + x + "," + y + ")";
}
0

That's a string interpolation operator. $ - string interpolation

It allows you to insert C# expressions inside a string block. The problem with your code seems to be the unnecessary space between the $ operator and your string.

chaosifier
  • 2,666
  • 25
  • 39
0

its not available in C# 5 or lower for your info

Shubham
  • 443
  • 2
  • 10
0

$ is short-hand for String.Format and is used with string interpolations, which is a new feature of C# 6. See here

In your case it's the same as

string.Format("({0},{1})", x, y);

But no spaces between $ and " is allowed. So you should use

$"({x},{y})" (no space after $)

hce
  • 1,107
  • 9
  • 25