Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do dollar symbols in C# Code mean?

Tags:

c#

c#-6.0

Today, I pull the code from my client, and I get an error in this line.

throw new Exception($"One or more errors occurred during removal of the company:{Environment.NewLine}{Environment.NewLine}{exc.Message}");

This line also

moreCompanies = $"{moreCompanies},{databaseName}";

The $ symbols is so weird with me. This is C# code.

like image 976
user3682707 Avatar asked Jul 31 '15 07:07

user3682707


People also ask

What does dollar sign do in C?

The dollar sign $ is a valid identifier character in the Microsoft C++ compiler (MSVC). MSVC also allows you to use the actual characters represented by the allowed ranges of universal character names in identifiers.

Can dollar sign be used in variable in C?

Unlike in other languages (bash, perl), C does not use $ to denote the usage of a variable. As such, it is technically valid.

Is dollar sign an operator?

The dollar sign, $ , is a controversial little Haskell operator. Semantically, it doesn't mean much, and its type signature doesn't give you a hint of why it should be used as often as it is. It is best understood not via its type but via its precedence.

What does the syntax dollar?

A $ with a selector specifies that it is a jQuery selector. It is given a shorter identifier as $ just to reduce the time for writing larger syntax. It contains all the functions that are used by a jQuery object such as animate(), hide(), show(), css() and many more.


1 Answers

The $ part tells the compiler that you want an interpolated string.

Interpolated strings are one of the new features of C# 6.0. They allow you to substitute placeholders in a string literal with their corresponding values.

You can put almost any expression between a pair of braces ({}) inside an interpolated string and that expression will be substituted with the ToString representation of that expression's result.

When the compiler encounters an interpolated string, it immediately converts it into a call to the String.Format function. It is because of this that your first listing is essentially the same as writing:

throw new Exception(string.Format(
    "One or more errors occured during removal of the company:{0}{1}{2}", 
    Envrionment.NewLine, 
    Environment.NewLine, 
    exc.Message));

As you can see, interpolated strings allow you to express the same thing in a much more succinct manner and in a way that is easier to get correct.

like image 98
Alex Booker Avatar answered Oct 25 '22 15:10

Alex Booker