C# Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 3.2

Data Literals - Example

This section provides a tutorial example on how to enter data literals into C# programs. 5 types of data literals used in C#: Boolean, Integer, Real, Character and String.

Now let's apply what we have learned so far, and write the following experimental program with literals.cs as the file name:

// Literals.cs
// Copyright (c) 2010 by Dr. Herong Yang, herongyang.com

class Literals {
   public static void Main() {      
      System.Console.WriteLine(
         "Boolean literals: {0} and {1}.", true, false);
      System.Console.WriteLine(
         "Integer literals: {0}, {1}, {2}, {3}.", 0, 555, -777, 911);
      System.Console.WriteLine(
         "Real literals: {0}, {1}, {2}, {3}.", 0.0, 555.0, -777.0,
         3.14159);
      System.Console.WriteLine(
         "Character literals: {0}, {1}, {2}, {3}.", 'a', 'A', '0',
         '9');
      System.Console.WriteLine(
         "Character literals: {0}, {1}, {2}, {3}, {4}.", '\t', '\r', 
         '\n', '\"', '\\');
      System.Console.WriteLine(
         "String literals: {0}, {1}, {2}.", "911", "Hello world!", 
         "Joe said \"Hello\" to me.");
   }
}

After compiling and executing the program, we will get the following output:

Boolean literals: True and False.
Integer literals: 0, 555, -777, 911.
Real literals: 0, 555, -777, 3.14159.
Character literals: a, A, 0, 9.
, aracter literals:     ,
, ", \.
String literals: 911, Hello world!, Joe said "Hello" to me..

There are a couple of interesting things to be noted here:

  • The boolean literal "true" is converted to a string with an upper case "T".
  • The real literal "0.0" is converted to a string with the trailing ".0" removed.
  • The character literals for special commands are executed while being displayed on the screen. The tab command '\t' pushed the next character ',' to the next tab position with several space characters. The return command '\r' pushed the next character back to the beginning of the line and whipped out the original character 'C'. The new line command '\n' forced the display process to move the next line.

Last update: 2010.

Table of Contents

 About This Book

 Introduction of C# (C Sharp)

Data Type and Variables

 Data Literals

Data Literals - Example

 Variables and Assignment Statements

 Variables and Assignments - Example

 Arithmetic Operations

 Arithmetic Operations - Example

 Logical Expressions and Conditional Statements

 Arrays and Loop Statements

 Data Type Features

 Floating-Point Data Types

 Passing Parameters to Methods

 Execution Environment Class

 Visual C# 2010 Express Edition

 Class Features

 C# Compiler and Intermediate Language

 Compiling C# Source Code Files

 Memory Usages of Processes

 Multithreading in C#

 System.IO.FileInfo Class

 System.Diagnostics.FileVersionInfo Class

 References

 PDF Printing Version

Dr. Herong Yang, updated in 2012
Data Literals - Example