Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

c# 6.0 - What do dollar symbols in C# Code mean?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...