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

Index initializers

You need to remember that C# 6.0 does not introduce big new concepts, but small features designed to make your code cleaner and easier to read and understand. With index initializers, this is not an exception. You can now initialize the indices of newly created objects. This means you do not have to use separate statements to initialize the indexes.

Getting ready

The change here is subtle. We will create a method to return the day of the week based on an integer. We will also create a method to return the start of the financial year and salary increase month, and then set the salary increase month to a different value than the default. Finally we will use properties to return a specific type of species to the console window.

How to do it…

  1. Start off by creating a new class called Recipe4IndexInitializers and add a second class called Month to your code. The Month class simply contains two auto-implemented properties that have been initialized. StartFinancialYearMonth has been set to month two (February), and SalaryIncreaseMonth has been set to month three (March):
    public static class Recipe4IndexInitializers
    {
    
    }
        
    public class Month
    {
        public int StartFinancialYearMonth { get; set; } = 2;
        public int SalaryIncreaseMonth { get; set; } = 3;
    }
  2. Go ahead and add a method called ReturnWeekDay that takes an integer for the day number as a parameter, to the Recipe4IndexInitializers class:
    public static string ReturnWeekDay(int dayNumber)
    {
        Dictionary<int, string> day = new Dictionary<int, string>
        {
            [1] = "Monday",
            [2] = "Tuesday",
            [3] = "Wednesday",
            [4] = "Thursday",
            [5] = "Friday",
            [6] = "Saturday",
            [7] = "Sunday"
        };
    
        return day[dayNumber];
    }
  3. For the second example, add a method called ReturnFinancialAndBonusMonth to the Recipe4IndexInitializers class:
    public static List<int> ReturnFinancialAndBonusMonth()
    {
        Month currentMonth = new Month();
        int[] array = new[] { currentMonth.StartFinancialYearMonth, currentMonth.SalaryIncreaseMonth };
        return new List<int>(array) { [1] = 2 };  
    }
  4. Finally, add several auto-implemented properties to the class to contain species and a method called DetermineSpecies to the Recipe4IndexInitializers class. Your code should look like this:
    public static string Human { get; set; } = "Homo sapiens";
    public static string Sloth { get; set; } = "Choloepus hoffmanni";
    public static string Rabbit { get; set; } = "Oryctolagus cuniculus";
    public static string Mouse { get; set; } = "Mus musculus";
    public static string Hedgehog { get; set; } = "Erinaceus europaeus";
    public static string Dolphin { get; set; } = "Tursiops truncatus";
    public static string Dog { get; set; } = "Canis lupus familiaris";
    
    public static void DetermineSpecies()
    {
        Dictionary<string, string> Species =  new Dictionary<string, string>
        {
            [Human] = Human + " : Additional species information",
            [Rabbit] = Rabbit + " : Additional species information",
            [Sloth] = Sloth + " : Additional species information",
            [Mouse] = Mouse + " : Additional species information",
            [Hedgehog] = Hedgehog + " : Additional species information",
            [Dolphin] = Dolphin + " : Additional species information",
            [Dog] = Dog + " : Additional species information"
        };
    
        Console.WriteLine(Species[Human]);            
    }
  5. In your console application, add the following code to call the code in the Recipe4IndexInitializers class:
    int DayNumber = 3;
    string DayOfWeek = Chapter1.Recipe4IndexInitializers.ReturnWeekDay(DayNumber);
    Console.WriteLine($"Day {DayNumber} is {DayOfWeek}");
                            
    List<int> FinancialAndBonusMonth = Chapter1.Recipe4IndexInitializers.ReturnFinancialAndBonusMo nth();
    Console.WriteLine("Financial Year Start month and Salary Increase Months are:");
    for (int i = 0; i < FinancialAndBonusMonth.Count(); i++)
    {
        Console.Write(i == 0 ? FinancialAndBonusMonth[i].ToString() + " and " : FinancialAndBonusMonth[i].ToString());
    }
    
    Console.WriteLine();
    Chapter1.Recipe4IndexInitializers.DetermineSpecies();
    Console.Read();
  6. Once you have added all your code, run your application. The output will look like this:
    How to do it…

How it works…

The first method ReturnWeekDay created a Dictionary<int, string> object. You can see how the indices are initialized with the day names. If we now pass the day integer to the method, we can return the day name by referencing the index.

Note

The reason for not using a zero-based index in ReturnWeekDay is because the first day of the week is associated to the numerical value 1.

In the second example, we called a method called ReturnFinancialAndBonusMonth that creates an array to hold the financial year start month and the salary increase month. Both properties of the Month class are initialized to 2 and 3, respectively. You can see that we are overriding the value of the SalaryIncreaseMonth property and setting it to 2. It is done in the following line of code:

return new List<int>(array) { [1] = 2 };

The last example uses the Human, Rabbit, Sloth, Mouse, Hedgehog, Dolphin, and Dog properties to return the correct index value of the Species object.

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