C# Escape Characters

This article is also available on the Microsoft TechNet Wiki.

Like other C-based languages, C# makes use of Escape Sequences or Escape Characters when working with string literals. Escape characters are designed to ensure that special text in a string literal appears as it should. The most common usages are for single and double quotes, tabbed spaces, and new line characters. Every escape character begins with a backslash (\) and is followed by a value or token.

The most common escape characters are represented in the table below:

Escape Character Representation
\’ Single quotation mark
\” Double quotation mark
\\ Backslash (useful for file and network paths definitions)
\? Literal question mark
\a System alert (beep)
\b Backspace
\f Formfeed (next page)
\n New line
\r Carriage return (beginning of a line)
\t Horizontal tab
\v Vertical tab

Note: If a character that does not appear in the table above is preceded with a backslash, the character value is returned. For example, if the compiler sees \x it will be treated as x.

Microsoft Technical Guru – July 2015

The Microsoft TechNet Guru Awards! (July 2015) have been announced and for another month I have been selected as a winner.

This month two articles have been chosen for medals. The TechNet Wiki articles were entered in the Visual C# Technical Guru category.

The first article was entitled Using the Checked and Unchecked keywords in C# to perform overflow checking. It won a Silver Medal in the Visual C# category.

The second article was Toolbox searching in Visual Studio 2013. It won a Bronze Medal in the Visual C# category.

JulyGuru

These wins brings my total number of TechNet Guru medals to eight.

Thanks to the judges for all their hard work and kind comments. And thank you to everyone at TechNet Wiki who makes this competition possible.

Related Articles:

My Wiki Ninja interview on TechNet

This year I have ramped up my work on the Microsoft TechNet Wiki. The site is a community resource where you can create articles on topics of interest to you. As with other wiki sites, communal editing of each other’s work is also encouraged to make the site the best it can be.

Part of the fun of the site is the perks you receive if you are an active user. You can enter your wiki articles into the monthly TechNet Guru Awards where they are judged by your peers within many different categories. The top three articles within each are then awarded medals and you become a TechNet Guru for that category. I am excited to say that I have personally won a few medals. For an updated list of my winning wiki articles please see my User Page.

Another nice thing the site does is have interviews with Wiki Ninjas. A Wiki Ninja is an active user within the TechNet Wiki community. This past week it was my turn to be interviewed. It was a fun experience and I want to thank Ed Price at Microsoft for thinking of me.

You can read my full interview here: Interview with .NET Developer, Microsoft MVP, and Wiki Ninja: Ken Cenerelli

Using the Checked and Unchecked keywords in C# to perform overflow checking

This article is also available on the Microsoft TechNet Wiki.

This article won a silver medal in The Microsoft TechNet Guru Awards! (July 2015).

Overview

In C#, the Integer type is used a lot to store values within methods. Often we do not think about the limits that the Integer has. By default, the maximum value it can hold is 2147483647. If we try to cram more into an Integer we receive an overflow error as the range has been met.

The Checked keyword is a way to see if integer arithmetic, including casts, can hold a value and if not it will generate a System.OverflowException error that can be handled elegantly. This keyword has been around since Visual Studio 2003 but little has been written on it. This article will examine how to use the Checked and Unchecked keywords.

Constant Values

Only constant values will cause the checked expression to fail. If the value is not a constant then it will not raise an overflow exception.

For example, the following line:

int x = 2147483647 + 1;

will generate an error message stating “The operation overflows at compile time in checked mode”.

However, doing any work with non-constant values will not display an error. In this line we will use a variable to add 1 to the maximum integer value:

int y = 1;
int x = 2147483647 + y;
Console.WriteLine(x);

This expression will not raise an error message. Instead, it will sum the value of two positive integers and produce a negative result:  -2147483648.

Checked Keyword

You can do overflow checking with compiler options or with the Checked keyword on an expression or method.

To use the compiler option, you can set the /checked option on the Build tab of the project’s properties to check for integer overflows which will cause an exception at run time. This will check all of your code automatically but at a cost
as it might slow down your program to do so. For more information about this option, see
/checked (C# Compiler Options).

For expression checking, wrap the statement you wish to validate in the checked value:

int x = checked(2147483647 + 1);

You can also check blocks of code encapsulated in braces:

checked {
  int y = 1;
  int x = 2147483647 + y;
  Console.WriteLine(x);
}

The keyword will only validate the code inside the braces. If your code calls other methods they will not be verified by the Checked keyword.

Both examples above raise an overflow exception. Following best practices, wrap these values in a try-catch block so as to handle the raised exception:

using System;

public class Program
{
  static int maxIntValue = 2147483647;

  public static void Main()
  {
    Console.WriteLine(CheckedMethod());
  }

  static int CheckedMethod()
  {
    int x = 0;
    try
    {
      x = checked (maxIntValue + 1);
    }
    catch (System.OverflowException e)
    {
      Console.WriteLine("Overflow exception due to unchecked integer value: " + e.ToString());
    }

    return x;
  }
}

The code above will generate the following error: Overflow exception due to unchecked integer value: System.OverflowException: Arithmetic operation resulted in an overflow.

Unchecked

C# also has the Unchecked keyword. This will allow you prevent overflow checking on certain items. It can be applied to expressions within a Checked method or to entire blocks of code if you have enabled the compiler option. This keyword is useful if want to label multiple items as Checked with a single line as Unchecked.

Conclusion

The Checked/Unchecked keywords are useful for trapping arithmetic overflows of integer values. It provides a way to elegantly trap for these occurrences and to handle the errors gracefully.

Some best practices to observe when using the keywords are:

  1. Only use the Checked/Unchecked keywords when an overflow is possible.
  2. Do not turn on the Compiler option in Release mode.
  3. Checked will not prevent a DivideByZeroException when a divide by zero is attempted.

References

Microsoft Technical Guru – June 2015

The Microsoft TechNet Guru Awards! (June 2015) have been announced and for the fourth straight month I have been selected as a winner.

This month two articles have been chosen for medals with a mention for a third. The TechNet Wiki articles were entered in the following categories:

  • Wiki and Portals Technical Guru – June 2015
  • Visual C# Technical Guru – June 2015
  • Microsoft Azure Technical Guru – June 2015

The first article was entitled  Wiki: How to Subscribe to the Wiki Ninjas Blog through RSS in Outlook 2013. It won a Gold Medal in the Wiki and Portals category:

01JuneGuru

The second article was How to enable line numbers for C# in Visual Studio 2013. It won a Bronze Medal in the Visual C# category:

02JuneGuru

The third article was Azure portal keyboard shortcuts. It received a mention in the Microsoft Azure category:

03JuneGuru

These wins brings my total number of TechNet Guru medals to six.

Thanks to the judges for all their hard work and kind comments. And thank you to everyone at TechNet Wiki who makes this competition possible.

Related Articles:

Follow

Get every new post delivered to your Inbox.