Book Image

C# Programming Cookbook

By : Dirk Strauss
Book Image

C# Programming Cookbook

By: Dirk Strauss

Overview of this book

During your application development workflow, there is always a moment when you need to get out of a tight spot. Through a recipe-based approach, this book will help you overcome common programming problems and get your applications ready to face the modern world. We start with C# 6, giving you hands-on experience with the new language features. Next, we work through the tasks that you perform on a daily basis such as working with strings, generics, and lots more. Gradually, we move on to more advanced topics such as the concept of object-oriented programming, asynchronous programming, reactive extensions, and code contracts. You will learn responsive high performance programming in C# and how to create applications with Azure. Next, we will review the choices available when choosing a source control solution. At the end of the book, we will show you how to create secure and robust code, and will help you ramp up your skills when using the new version of C# 6 and Visual Studio
Table of Contents (21 chapters)
C# Programming Cookbook
Credits
About the Author
Acknowledgements
About the Reviewer
www.PacktPub.com
Preface
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:

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.