C# Tips eBook Complete

I’m pleased to announce that my C# Tips eBook is now complete and currently has over 1,000 readers.

The book is free and you may pay whatever you can afford.

https://s3.amazonaws.com/titlepages.leanpub.com/cstips/large?1416887188

 

Thanks to all the readers who supported the writing of this book.

Download C# Tips today.

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

Progress Update on C# Tips eBook

An updated version of my C# Tips eBook has just been released. This brings the book to around 80% complete.

The book includes useful C# Tips, design patterns, and tools.

The remaining 20% of effort will include continuing to add new content, arranging and ordering existing content, cross referencing and final proof reading.

Check out the book on Leanpub.

SHARE:

C# Tips eBook 50% Complete

I just published a new version of my C# Tips eBook that marks the half way point of the project.

C# Tips is available in PDF, EPUB, and MOBI.

The book is scheduled for completion by the end of the year and has 521 readers at present. It is currently free, you may also pay whatever you think it’s worth.

You can download it now from Leanpub.

An abridged copy of the current table of contents is shown below.

  • Merging IEnumerable Sequences with LINQ
  • Auto-Generating Sequences of Integer Values
  • Improving Struct Equality Performance
  • Creating Generic Methods in Non-Generic Classes
  • Converting Chars to Doubles
  • Non Short Circuiting Conditional Operators Using C# Keywords for Variable Names
  • Three Part Conditional Numeric Format Strings
  • Customizing the Appearance of Debug Information in Visual Studio
  • Partial Types
  • The Null Coalescing Operator
  • Creating and Using Bit Flag Enums
  • The Continue Statement
  • Preprocessor Directives
  • Automatically Stepping Through Code
  • Exceptions in Static Constructors
  • Safe Conversion To and From DateTime Strings
  • Parsing Strings into Numbers with NumberStyles
  • Useful LINQ Set Operations
  • The Decorator Pattern
  • The Factory Pattern
  • NUnit
  • xUnit.net

SHARE:

Handling CTRL-C in .NET Console Applications

By default, pressing CTRL-C while a console application is running will cause it to terminate.

If we want to prevent this we can set Console.TreatControlCAsInput Property to true. This will prevent CTRL-C from terminating the application. To terminate now, the user needs to close the console window or hit CTRL-BREAK instead of the more usual and well-known CTRL-C.

class Program
{
    private static void Main(string[] args)
    {
        Console.TreatControlCAsInput = true;
        while (true)
        {
        }
    }
}

There is also the Console.CancelKeyPress event. This event is fired whenever CTRL-C or CTRL-BREAK is pressed. It allows us to decide whether or not to terminate the application.

More...

SHARE:

Getting Input From Alternative Sources in .NET Console Applications

Using the Console.SetIn Method allows us to specify an alternative source (TextReader stream).

For example suppose we have the following “names.txt” text file:

Sarah
Amrit
Gentry
Jack

We can create a new stream that reads from this file whenever we perform a Console.ReadLine(). Now when we call ReadLine, a line is read from the text file rather than the keyboard.

We can use the Console.OpenStandardInput() method to reset input back to the keyboard.

The code below creates the following output:

More...

SHARE:

Creating a Spinner Animation in a Console Application in C#

If we have a longer running process taking place in a console application, it’s useful to be able to provide some feedback to the user so they know that the application hasn’t crashed. In a GUI application we’d use something like an animated progress bar or spinner. In a console application we can make use of the SetCursorPosition() method to keep the cursor in the same place while we output characters, to create a spinning animation.

consolespinner1

While the code below could certainly be improved, it illustrates the point:

More...

SHARE:

Setting Foreground and Background Colours in .NET Console Applications

In addition to doing some fun/weird/useful/annoying things in Console applications, we can also set foreground and background colours.

To set colours we use the Console.BackgroundColor and Console.ForegroundColor properties.

When we set these properties we supply a ConsoleColor. To reset the colours back to the defaults we can call the ResetColor() method.

using System;

namespace ConsoleColorDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Default initial color");

            Console.BackgroundColor = ConsoleColor.White;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.WriteLine("Black on white");
            Console.WriteLine("Still black on white");

            Console.ResetColor();

            Console.WriteLine("Now back to defaults");

            Console.ReadLine();

        }
    }
}

The above code produces the following output:

More...

SHARE:

3 Surprising Things to Do with the Console in C#

The Console class can do more than just WriteLine().

Here’s 3 fun/weird/useful/annoying things.

1. Setting The Console Window Size

The Console.SetWindowSize(numberColumns, numberRows) method sets the console window size.

Console.SetWindowSize

 

To annoy your users (or create a “nice” console opening animation) as this animated GIF shows you could write something like:

for (int i = 1; i < 40; i++)
{
    Console.SetWindowSize(i,i);
    System.Threading.Thread.Sleep(50);
}

2. Beeping Consoles

The Console.Beep() method emits a beep from the speaker(s).

We can also specify a frequency and duration.

More...

SHARE:

Merging IEnumerable Sequences in C# with LINQ

The Zip method allows us to join IEnumerable sequences together by interleaving the elements in the sequences.

Zip is an extension method on IEnumerable. For example to zip together a collection of names with ages we could write:

var names = new [] {"John", "Sarah", "Amrit"};

var ages = new[] {22, 58, 36};

var namesAndAges = names.Zip(ages, (name, age) => name + " " + age);    

This would produce an IEnumerable<string> containing three elements:

  • “John 22”
  • “Sarah 58”
  • “Amrit 36”

If one sequence is shorter that the other, the “zipping” will stop when the end of the shorter sequence is reached. So if we added an extra name:

var names = new [] {"John", "Sarah", "Amrit", "Bob"};

We’d end up with the same result as before, “Bob” wouldn’t be used as there isn’t a corresponding age for him.

We can also create objects in our lambda, this example shows how to create an IEnumerable of two-element Tuples:

var names = new [] {"John", "Sarah", "Amrit"};

var ages = new[] {22, 58, 36};

var namesAndAges = names.Zip(ages, (name, age) => Tuple.Create(name, age)); 

This will produce an IEnumerable<Tuple<String,Int32>> that contains three Tuples, with each Tuple holding a name and age.

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE: