Subscribe

RSS Feed (xml)

C# Literals

In C#, literals refer to fixed values that are represented in their human-readable form. For example, the number 100 is a literal. Literals are also commonly called constants. For the most part, literals and their usage are so intuitive that they have been used in one form or another by all the preceding sample programs. Now the time has come to explain them formally.

C# literals can be of any value type. The way each literal is represented depends upon its type. As explained earlier, character constants are enclosed between single quotes. For example, ‘a’ and ‘%’ are both character constants.

Integer literals are specified as numbers without fractional components. For example, 10 and 100 are integer constants. Floating-point constants require the use of the decimal point followed by the number’s fractional component. For example, 11.123 is a floating-point constant. C# also allows you to use scientific notation for floating-point numbers.

Since C# is a strongly typed language, literals, too, have a type. Naturally, this raises the following question: What is the type of a numeric literal? For example, what is the type of 12, 123987, or 0.23? Fortunately, C# specifies some easy-to-follow rules that answer these questions.

First, for integer literals, the type of the literal is the smallest integer type that will hold it, beginning with int. Thus, an integer literal is either of type int, uint, long, or ulong, depending upon its value. Second, floating-point literals are of type double.

If C#’s default type is not what you want for a literal, you can explicitly specify its type by including a suffix. To specify a long literal, append an l or an L. For example, 12 is an int, but 12L is a long. To specify an unsigned integer value, append a u or U. Thus, 100 is an int, but 100U is a uint. To specify an unsigned, long integer, use ul or UL. For example, 984375UL is of type ulong.

To specify a float literal, append an F or f to the constant. For example, 10.19F is of type float.

To specify a decimal literal, follow its value with an m or M. For example, 9.95M is a decimal literal.

Although integer literals create an int, uint, long, or ulong value by default, they can still be assigned to variables of type byte, sbyte, short, or ushort as long as the value being assigned can be represented by the target type. An integer literal can always be assigned to a long variable.

Hexadecimal Literals

As you probably know, in programming it is sometimes easier to use a number system based on 16 instead of 10. The base 16 number system is called hexadecimal and uses the digits 0 through 9, plus the letters A through F, which stand for 10, 11, 12, 13, 14, and 15. For example, the hexadecimal number 10 is 16 in decimal. Because of the frequency with which hexadecimal numbers are used, C# allows you to specify integer constants in hexadecimal format. A hexadecimal literal must begin with 0x (a zero followed by an x). Here are some examples:

count = 0xFF; // 255 in decimal
incr = 0x1a;  // 26 in decimal

Character Escape Sequences

Enclosing character constants in single quotes works for most printing characters, but a few characters, such as the carriage return, pose a special problem when a text editor is used. In addition, certain other characters, such as the single and double quotes, have special meaning in C#, so you cannot use them directly. For these reasons, C# provides special escape sequences, sometimes referred to as backslash character constants. These sequences are used in place of the characters that they represent.

Character Escape Sequences

Escape Sequence

Description

\a

Alert (bell)

\b

Backspace

\f

Form feed

\n

New line (linefeed)

\r

Carriage return

\t

Horizontal tab

\v

Vertical tab

\0

Null

\

Single quote

\

Double quote

\\

Backslash

For example, this assigns ch the tab character:

ch = '\t';

The next example assigns a single-quote to ch:

ch = '\'';

String Literals

C# supports one other type of literal: the string. A string is a set of characters enclosed by double quotes. For example,

"this is a test"

is a string. You have seen examples of strings in many of the WriteLine( ) statements in the preceding sample programs.

In addition to normal characters, a string literal can also contain one or more of the escape sequences just described. For example, consider the following program. It uses the \n and \t escape sequences.

// Demonstrate escape sequences in strings.

using System;

class StrDemo {
 public static void Main() {
   Console.WriteLine("Line One\nLine Two\nLine Three");
   Console.WriteLine("One\tTwo\tThree");
   Console.WriteLine("Four\tFive\tSix");
 
   // embed quotes
   Console.WriteLine("\"Why?\" he asked.");
 }
}

The output is shown here:

Line One
Line Two
Line Three
One     Two     Three
Four    Five    Six
"Why?" he asked.

Notice how the \n escape sequence is used to generate a new line. You don’t need to use multiple WriteLine( ) statements to get multiline output. Just embed \n within a longer string at the points at which you want the new lines to occur. Also note how a quotation mark is generated inside a string.

In addition to the form of string literal just described, you can also specify a verbatim string literal. A verbatim string literal begins with an @, which is followed by a quoted string. The contents of the quoted string are accepted without modification and can span two or more lines. Thus, you can include newlines, tabs, and so on, but you don’t need to use the escape sequences. The only exception is that to obtain a double-quote ("), you must use two double-quotes in a row (""). Here is a program that demonstrates verbatim string literals:

// Demonstrate verbatim literal strings.

using System;

class Verbatim {
 public static void Main() {
   Console.WriteLine(@"This is a verbatim
string literal
that spans several lines.
");
   Console.WriteLine(@"Here is some tabbed output:
1     2     3     4
5     6     7     8
");
   Console.WriteLine(@"Programmers say, ""I like C#.""");
 }
}

The output from this program is shown here:

This is a verbatim
string literal
that spans several lines.

Here is some tabbed output:
1       2       3       4
5       6       7       8

Programmers say, "I like C#."

The important point to notice about the preceding program is that the verbatim string literals are displayed precisely as they are entered into the program.

The advantage of verbatim string literals is that you can specify output in your program exactly as it will appear on the screen. However, in the case of multiline strings, the wrapping will cause the indentation of your program to be obscured. For this reason, the programs in this book will make only limited use of verbatim string literals. That said, they are still a wonderful benefit for many formatting situations.

One last point: Don’t confuse strings with characters. A character literal, such as ‘X’, represents a single letter of type char. A string containing only one letter, such as “X”, is still a string.

2 comments:


  1. It is really a great work and the way in which u r sharing the knowledge is excellent.Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article.
    Dot Net Training in chennai | Dot Net Training in velachery

    ReplyDelete
  2. C# literals can be of any value type. The way each literal is represented depends upon its type. dot net training and placement in chennai | dot net training in chennai

    ReplyDelete

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail