Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
C# Programming Cookbook

You're reading from   C# Programming Cookbook Quick fixes to your common C# programming problems, with a focus on C# 6.0

Arrow left icon
Product type Paperback
Published in Jul 2016
Publisher Packt
ISBN-13 9781786467300
Length 476 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Dirk Strauss Dirk Strauss
Author Profile Icon Dirk Strauss
Dirk Strauss
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. New Features in C# 6.0 FREE CHAPTER 2. Classes and Generics 3. Object-Oriented Programming in C# 4. Composing Event-Based Programs Using Reactive Extensions 5. Create Microservices on Azure Service Fabric 6. Making Apps Responsive with Asynchronous Programming 7. High Performance Programming Using Parallel and Multithreading in C# 8. Code Contracts 9. Regular Expressions 10. Choosing and Using a Source Control Strategy 11. Creating a Mobile Application in Visual Studio 12. Writing Secure Code and Debugging in Visual Studio 13. Creating a Web Application in Azure Index

String interpolation

String interpolation is a very easy and precise way to inject variable values into a string. An interpolated string expression looks at contained expressions. It then replaces those expressions with the ToString representations of the expressions' results.

Getting ready

Create a new class to test your code. We will use the example of reading the current exchange rate for a specific currency to illustrate how string interpolation can be used to output strings to the user interface.

How to do it…

  1. Create a new class by right-clicking on your solution, selecting Add, and then selecting New Project from the context menu:
    How to do it…
  2. From the Add New Project dialog screen, select Class Library from the installed templates and call your class Chapter1:
    How to do it…
  3. Your new class library will be added to your solution with a default name of Class1.cs, which I renamed to Recipes.cs in order to distinguish the code properly. You can, however, rename your class to whatever you like if that makes more sense to you.
  4. To rename your class, simply click on the class name in Solution Explorer and select Rename from the context menu:
    How to do it…
  5. Visual Studio will ask you to confirm a rename of all references to the Class1 code element in the project. Just click on Yes:
    How to do it…
  6. The class that is created now needs to be made static using the static keyword. Also, rename the class name in code to Recipe1StringInterpolation:
    namespace Chapter1
    {
        public static class Recipe1StringInterpolation
        {
    
        }
    }

    Note

    Note that static classes, therefore, do not need to be instantiated and will be sealed classes by default. This means that they cannot be inherited further. In practice, you would normally define helper or utility classes as static. These are classes that will be used often by your application to, for example, parse dates or perform calculations. The use of the static keyword here is simply to illustrate the specific new features of C# 6.0 within a class that can easily and quickly be called from the console application. The static class in reality would most likely not be a good fit for all the examples illustrated.

  7. Inside your class, add a property to contain the base currency:
    public static string BaseCurrency { get; private set; }
  8. Next, include a dummy method to return the exchange rate:
    private static decimal PreformConversion(string toCurrency)
    {
        decimal rate = 0.0m;
    
        if (BaseCurrency.Equals("ZAR"))
        {
            switch (toCurrency)
            {
                case "USD":
                    rate = 16.3040m;
                    break;
                default:
                    rate = 1.0m;
                    break;
            }
        }
                
        return rate;
    }
  9. The last method to add is the method that will return the interpolated string expression:
    public static string ReadExchangeRate(string fromCurrencyCode, string toCurrencyCode)
    {
        BaseCurrency = fromCurrencyCode;
        decimal conversion = PreformConversion(toCurrencyCode);
        return $"1 {toCurrencyCode} = {conversion} {fromCurrencyCode} ";
    }
  10. You now need to hook up the class you created to your console application. You therefore need to add a reference to the class from the console application. Right-click on References in your CodeSamples project and select Add Reference…:
    How to do it…
  11. From the Reference Manager dialog that pops up, select the Chapter1 solution to add it as a reference. Then, click on the OK button:
    How to do it…
  12. In your CodeSamples project, double-click on the Program.cs file and add the following code to the Main method:
    string RandDollarExchangeRate = Chapter1.Recipe1StringInterpolation.ReadExchangeRate("ZAR", "USD");
    Console.WriteLine("The current Rand / Dollar exchange rate is:");
    Console.WriteLine(RandDollarExchangeRate);
    Console.Read();
  13. To see the result, run your application and see the output in the console application:
    How to do it…
  14. The interpolated string expression is output as 1 USD = 16,3040 ZAR.

How it works…

The console application passes the currency codes for South African Rand and US Dollar to the static class by calling the following line of code: Chapter1.Recipe1StringInterpolation.ReadExchangeRate("ZAR", "USD");

This class is static and, as mentioned previously, does not need to be instantiated. The ReadExchangeRate method then reads the exchange rate and formats it into a suitable string using string interpolation. You will notice that the interpolated string expression is written as $"1 {toCurrencyCode} = {conversion} {fromCurrencyCode} ";.

The toCurrencyCode, conversion, and fromCurrencyCode variables are expressed directly inside the string expression. This is a much easier way of formatting strings because you can do away with String.Format, used in the previous versions of C#. Previously, the same expression would have been written as String.Format("1 {0} = {1} {2} ", toCurrencyCode, conversion, fromCurrencyCode);.

As you can see, the interpolated string expression is much easier to read and write. In reality though, string interpolation is merely syntactical sugar because the compiler treats the expression like String.Format anyway. You might be wondering how you would express a curly bracket when using string interpolation. To do this, you can simply use a double curly bracket in your expression. If you need to express the exchange rate as {16,3040}, you would need to express it as $"{{{conversion}}}";.

You can also format your string right there inside the interpolated string expression. If you returned the $"The date is {DateTime.Now}"; expression, the output would be The date is 2016/01/10 3:04:48 PM. You can go ahead and modify the expression to format the date using a colon, followed by the format to use. Change the code to $"The date is {DateTime.Now : MMMM dd, yyyy}";. The output will be formatted and result in The date is January 5, 2016.

Another great tip is that you can express a condition in the string expression. Consider the following line of code that determines whether a year is a leap year or not:

$"The year {DateTime.Now.Year} {(DateTime.IsLeapYear(DateTime.Now.Year) ? " is " : " is not ")} a leap year.";

We can use the ternary ? operator one step further. Consider the following line of code:

$"There {(StudentCount > 1 ? "are " : "is ")}{StudentCount} student{(StudentCount > 1 ? "s" : "")} in the list."

As the colon is used to denote formatting, we have to wrap the conditional part of the expression in parenthesis. String interpolation is a very nice way to express strings in code that is easy to read and understand.

You have been reading a chapter from
C# Programming Cookbook
Published in: Jul 2016
Publisher: Packt
ISBN-13: 9781786467300
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime