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

Using static

C# 6.0 introduces a new kind of using statement that now refers to types instead of namespaces. This means that the static members of the type are then directly put into scope. What this means for your code is evident in the condensed result of this recipe.

Getting ready

We will create a class called Recipe7UsingStatic that will determine the sale price of an item depending on the day of the week. If it is Friday, we want to apply the sale discount to the item. On any other day, we will sell the item at the shelf price.

How to do it…

  1. Start by creating a Recipe7UsingStatic class that contains two auto-implemented properties and an enumerator for the day of the week:
    public static class Recipe7UsingStatic
    {
        public enum TheDayOfWeek
        {
            Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
        }
    
        private static int SaleDiscountPercent { get; } = 20;
        private static decimal ShelfPrice { get; set; } = 100;        
    }
  2. We will now add a computed property and two methods to our Recipe7UsingStatic class. One method will set the shelf price and the other will get the sale price:
    private static decimal GetCalculatedSalePrice
    {
        get { return Math.Round(ShelfPrice.CalculateSalePrice (SaleDiscountPercen t), 2); }
    }        
    
    public static void SetShelfPrice(decimal shelfPrice)
    {
        ShelfPrice = shelfPrice;
    }
    
    public static decimal GetSalePrice(TheDayOfWeek dayOfWeek)
    {
        return dayOfWeek == TheDayOfWeek.Friday ? GetCalculatedSalePrice : ShelfPrice;
    }
  3. In the console application, we will add the code to define the day of the week, set the shelf price, and then get the sale price. The sale price is then written out to the console application:
    decimal ShelfPrice = 56.99m;
    
    Chapter1.Recipe7UsingStatic.TheDayOfWeek weekday = Chapter1.Recipe7UsingStatic.TheDayOfWeek.Friday;
    Chapter1.Recipe7UsingStatic.SetShelfPrice(ShelfPrice);
    Console.WriteLine(Chapter1.Recipe7UsingStatic.GetSalePrice( weekday));
    Console.Read();

How it works…

Run your console application and see that the sale price is calculated correctly and output to the console application:

How it works…

Now, let's have a closer look at the code. In particular, look at the GetCalculatedSalePrice computed property. It uses the Math.Round function to round the sale price to two decimals:

private static decimal GetCalculatedSalePrice
{
    get { return Math.Round(ShelfPrice.CalculateSalePrice (SaleDiscountPercent), 2); }
}

The Math class is in reality a static class that contains a collection of functions that you can use throughout your code to perform different mathematical calculations. So, go ahead and add the following using statement at the top of your Recipes.cs file:

using static System.Math;

We can now change our computed GetCalculatedSalePrice property to omit the Math class name:

private static decimal GetCalculatedSalePrice
{
    get { return Round(ShelfPrice.CalculateSalePrice(SaleDiscountPercent), 2); }
}

This is really a fantastic enhancement. Look at the following lines of code:

Math.Sqrt(64);
Math.Tan(64);
Math.Pow(8, 2);

Because of this enhancement, the preceding lines of code can simply be written as follows:

Sqrt(64);
Tan(64);
Pow(8, 2);

There is, however, more to using the static keyword's functionality. We are using static classes for all the recipes in this chapter. We can, therefore, also implement the using static statement for our own custom static classes. Add the following using statements to the top of the console application's Program class:

using static Chapter1.Recipe7UsingStatic;
using static Chapter1.Recipe7UsingStatic.TheDayOfWeek;
using static System.Console;

You will notice that we have included the enumerator in the using static statements. This is equally fantastic, because Friday is clearly a day of the week, and the enumerator doesn't need to be called fully, as in the old console application code. By adding the using static statements, the code in our console application can be changed as follows:

TheDayOfWeek weekday = Friday;
SetShelfPrice(ShelfPrice);
WriteLine(GetSalePrice(weekday));
Read();

This is where the real benefit of the using static statements become evident. It means less code and makes your code more readable. To recap the idea behind C# 6.0, it didn't introduce big new concepts but many small features to make your code cleaner and your intent easier to understand. The using static feature does exactly this.

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