Book Image

The Modern C# Challenge

By : Rod Stephens
Book Image

The Modern C# Challenge

By: Rod Stephens

Overview of this book

C# is a multi-paradigm programming language. The Modern C# Challenge covers with aspects of the .NET Framework such as the Task Parallel Library (TPL) and CryptoAPI. It also encourages you to explore important programming trade-offs such as time versus space or simplicity. There may be many ways to solve a problem and there is often no single right way, but some solutions are definitely better than others. This book has combined these solutions to help you solve real-world problems with C#. In addition to describing programming trade-offs, The Modern C# Challenge will help you build a useful toolkit of techniques such as value caching, statistical analysis, and geometric algorithms. By the end of this book, you will have walked through challenges in C# and explored the .NET Framework in order to develop program logic for real-world applications.
Table of Contents (17 chapters)
Title Page
Copyright and Credits
Dedication
Packt Upsell
Contributors
Preface
Free Chapter
1
Mathematics
3
Dates and Times
4
Randomization
6
Files and Directories
7
Advanced C# and .NET Features
Index

Preface

So you've read an introductory book and perhaps one or two more advanced books. You've worked with C# for a while and now you're ready for something that wasn't written for idiots or dummies. This book may be just the thing!

This book includes 100 problems (with solutions) that you can use to test and hone your C# programming skills. They cover an eclectic assortment of topics, such as mathematical calculations, geometry, dates and times, the filesystem, simulations, and cryptography. These problems won't make you an expert in those fields, but they will give you some experience with a wide variety of useful topics.

As with many skills, the best way to learn programming is to practice. Most programming books cover roughly the same topics, so they don't give you the opportunity to practice skills that fall into the programming nooks and crannies that those books miss. They do a good job of covering basic topics, such as forms, controls, classes, and for loops. More advanced books also cover more specialized topics, such as algorithms (I've written a few algorithms books), databases, web programming, and phone apps. Few books have room for more specialized topics, such as mathematical calculations, simulations, and cryptography. You'll get a brief introduction to those topics here.

In addition to giving you practice with some of programming's less heavily-trodden byways, many of the examples in this book demonstrate important C# programming concepts. They show how to protect your programs from integer and floating point overflow, avoid exhausting stack memory, know when LINQ or PLINQ might hurt performance, handle times in multiple time zones, and use the yield statement.

Two things that this book does not cover are console applications and WPF. The example solutions use Windows Forms programs because they are easy to write, and that lets you focus on the concepts behind the user interface instead of spending time fiddling with WPF issues.

Before I get to the problems themselves, the following sections explain some of the details of the book's layout, how to get the most out of the book, and how you can get in touch with the publisher. After you skim that material, find a comfortable chair, possibly in your favorite coffee shop or tea house with a caffeinated beverage and a scone, open your laptop, and get ready to give your brain a workout!

Who this book is for

This book is intended for C# programmers. It does not explain basic C# concepts, so you should have some familiarity with C# programming before you read it. The book does not assume that you are an expert C# developer, however. If you know basic techniques such as creating classes, writing methods, and working with arrays and lists, then you should be able to work through the problems and understand their solutions.

What this book covers

This book includes 100 problems to challenge you and help you develop your C# programming skills. The solutions rely on general programming methods rather than C# language minutiae, so you should have a chance to solve them even if you haven't been programming for decades. They demonstrate useful techniques, not the answers to trivia questions.

Many of the examples also demonstrate important development concepts, such as comparing floating point values, handling integer overflow, avoiding unnecessary recursion, working across time zones, and building simulations. Some examples also show how to use specific advanced C# and .NET Framework tools such as the yield statement, the Transact Parallel Library (TPL), and .NET cryptography classes.

The following paragraphs describe the book's chapters in some detail:

Chapter 1, Mathematics, describes problems that ask you to perform mathematical tasks. These include numerical tasks such as calculating statistical functions, factorials, and binomial coefficients. They also include some combinatorial tasks such as finding all of the permutations or combinations from a set of items.

Chapter 2, Geometry, presents problems that perform geometric calculations. These ask you to find values such as the roots of equations, the points where lines and circles intersect, and the areas of polygons. Many of these problems ask you to draw shapes such as lines, circles, arrowheads, polygons, and stars.

Chapter 3, Dates and Times, includes problems that deal with dates and times. They pay special attention to programs that include multiple time zones or that include times when daylight saving time (or the equivalent in other countries) starts or ends.

Chapter 4, Randomization, poses problems that use randomization to produce various kinds of randomized data. For example, they ask you to generate random floating point numbers within a range, pick random items from a list or array, and generate random passwords.

 

Chapter 5, Strings, describes problems that manipulate strings. For example, they require you to convert between numbers and roman numerals and between bytes and hexadecimal strings, detect palindromic substrings, validate passwords for correctness, and use the Soundex algorithm to represent word's sound.

Chapter 6, Files and Directories, covers problems that deal with the filesystem. Its problems ask you to remove blank lines from a file, calculate a directory's total size, detect duplicate files, and generate thumbnails for image files in a directory.

Chapter 7, Advanced C# and .NET Features, includes problems that deal with more advanced features such as Language Integrated Query (LINQ), Parallel LINQ (PLINQ), Transact Parallel Library (TPL), and the yield statement.

Chapter 8, Simulations, asks you to write programs that perform simulations. Those range from simple numeric or text-based simulations (such as Dawkins' weasel and finding hailstone sequences), to positional simulations (such as Langton's ant and Life), to simulations that model gravitational force and acceleration.

Chapter 9, Cryptography, describes cryptographic problems. Some, such as the problems that deal with Caesar and Vigenère ciphers, are interesting mostly for fun and historical perspective. Others, such as those that deal with prime numbers, hashing, and string encryption, demonstrate strong, modern cryptographic methods.

You may not learn something new fromeveryproblem in the book, but hopefully you'll learn something from many of them.

To get the most out of this book

Programming is best learned by doing rather than by reading, so I strongly encourage you to try to solve a problem before you look at my example solution later in the book. I've tried to include all of the information that you need to solve each problem in its description, so you should be able to take a crack at it before you look at my solution.

Even if you get stuck on a problem, the beginning of the solution's description may help you figure out how to solve it. If you experience an Ah ha! moment while you're reading about the solution, stop and give it another try.

Keep in mind that there are always multiple ways to solve any particular problem. Some solutions may be better than others, but most problems can be solved by several different approaches, so don't think your solution is wrong just because it's different from mine. In fact, yours may be better than mine.

 

 

The easiest way to read this book is from front to back, tackling each problem in order. The chapters are arranged so the less confusing topics come first. Similarly, the problems within each chapter are arranged with the less demanding first. Some of the material described in one problem's solution may also be used in a later solution, so reading the problems and their solutions in order makes sense.

However, the problems and their example solutions are described separately, so you can jump around if you like. For example, if you are particularly interested in steganography, you can jump straight to Chapter 9Cryptography. The worst that will happen is that an example solution may refer you to an earlier solution for some of its details. You can then go back and read the earlier solution for further details.

 

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

  1. Log in or register at www.packt.com.
  2. Select the SUPPORT tab.
  3. Click on Code Downloads & Errata.
  4. Enter the name of the book in the Search box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR/7-Zip for Windows
  • Zipeg/iZip/UnRarX for Mac
  • 7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/The-Modern-CSharp-Challenge. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

 

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/9781789535426_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Several of the solutions in earlier chapters used the Random class to generate random numbers."

A block of code is set as follows:

private int FindError(string string1, string string2)
{
    int error = 0;
    for (int i = 0; i < string1.Length; i++)
        error += Math.Abs((int)string1[i] - (int)string2[i]);
    return error;
}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

{
    string testSubstring = string1.Substring(startPos, length);
    int testPos = string2.IndexOf(testSubstring);
    if (testPos < 0) break;

    bestLength = length;
    bestSubstring = testSubstring;
}

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "In the Add Item dialog, I selected the MP3 file and clicked Add."

 

 

Note

Warnings or important notes appear like this.

Note

Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.