C# Simplified, part 3

In this article you will learn about a variety of useful functionalities in C#. These include various escape characters; differing formats for numbers, dates, and time; arrays; and enumeration.

Contributed by
Rating: 3 stars3 stars3 stars3 stars3 stars / 12
May 17, 2005
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement


Files associated with this article can be downloaded here.


C# Simplified covers each and every concept of C# programming language in a concise manner. The articles in this series have been divided into several parts and will provide detailed explanations along with source codes and screenshots. This series has been specifically written for beginners and students with an aim to teach C# in the quickest possible time. Please send your comments to csharpsimplified@gmail.com

Different Types of Escape Characters in C#

C# provides a variety of ways to produce beep sounds when an error occurs, create tabs between words, print output with double quotes and much more. These functionalities can be achieved with the help of the built-in escape characters. Listing 3.1 illustrates each of these characters in detail. I have provided the necessary explanations in the form of comments

Listing 3.1

using System;

class Escape

{

public static void Main()

{

// Prints Welcome with a single beep from your CPU

Console.WriteLine("Single beep sound heard");

Console.WriteLine("\aWelcome");

// Prints elcome after deleting W due to Backspace escape character

Console.WriteLine("W\belcome");

// Prints Wel and Co and me in three lines

Console.WriteLine("Wel\nco\nme");

// Prints Welcome after a single tab position

Console.WriteLine("\tWelcome");

// Returns \Welcome\

Console.WriteLine("\\Welcome\\");

// Returns 'Welcome'

Console.WriteLine("\'Welcome\'");

// Returns "Welcome"

Console.WriteLine("\"Welcome\"");

}

}

The output of the above program looks like Figure 3.1

Figure 3.1

Displaying numbers in different formats

C# enables you to display numbers in different ways with the help of Format Specifiers. For example, you can display numbers with a currency symbol or with decimal places. These specifiers are enclosed within curly braces followed by the variable name of the specific value.

In Listing 3.2, a variable named i is declared and its value is displayed in different ways using a set of format specifiers. I have given necessary explanations as comments.

Listing 3.2

using System;

class NumberFormat

{

public static void Main()

{

int i = 7777;

// Returns the exact currency value with the symbol ($)

Console.WriteLine("{0:C}",i);

// Returns the Number converted to a string of decimal digits

Console.WriteLine("{0:D}",i);

// Returns the Expotential value

Console.WriteLine("{0:E}",i);

// Returns the fixed point string representation of the number

Console.WriteLine("{0:F}",i);

// Returns the most compact form of fixed point number

Console.WriteLine("{0:G}",i);

// Returns the number in the d,ddd,ddd.ddd format

Console.WriteLine("{0:N}",i);

// Returns the Uppercase hexadecimal digit of the converted number

Console.WriteLine("{0:X}",i);

// Returns the Lowercase hexadecimal digit of the converted number

Console.WriteLine("{0:x}",i);

}

}

The final output of the above program will look like Figure 3.2.

Figure 3.2

Format Specifiers combined with numbers are called Precision Specifiers. For example, if you use a format like C6, you will get six zeros appended after the decimal position of the number. Listing 3.3 shows a modified version of listing 3.2.

Listing 3.3

using System;

class NumberFormatPrecision

{

public static void Main()

{

int i = 7777;

// Returns the exact currency value with the symbol ($)

Console.WriteLine("{0:C5}",i);

// Returns the Number converted to a string of decimal digits

Console.WriteLine("{0:D5}",i);

// Returns the Expotential value

Console.WriteLine("{0:E5}",i);

// Returns the fixed point string representation of the number

Console.WriteLine("{0:F5}",i);

// Returns the most compact form of fixed point number

Console.WriteLine("{0:G5}",i);

// Returns the number in the d,ddd,ddd.ddd format

Console.WriteLine("{0:N5}",i);

// Returns the Uppercase hexadecimal digit of the converted number

Console.WriteLine("{0:X5}",i);

// Returns the Lowercase hexadecimal digit of the converted number

Console.WriteLine("{0:x5}",i);

}

}

The output of the above program looks like Figure 3.3.

Figure 3.3

Display date and time in different formats

You can display data and time in different ways with the help of DateTime format specifiers. Listing 3.4 explains each one of these specifiers in detail. I have given necessary explanations in the form of comments.

Listing 3.4

using System;

class DateTimeFormat

{

public static void Main()

{

DateTime dt = DateTime.Now;

// Returns Short Date (MM/DD/YYYY)

Console.WriteLine("Format Specifier (d): {0:d}",dt);

// Returns Long Date (Day, Month Date, Year)

Console.WriteLine("Format Specifier (D): {0:D}",dt);

// Returns Full Date with Time and without seconds

Console.WriteLine("Format Specifier (f):{0:f}",dt);

// Returns Full Date with Time and with Seconds

Console.WriteLine("Format Specifier (F):{0:F}",dt);

// Returns short date and short time without seconds

Console.WriteLine("Format Specifier (g):{0:g}",dt);

// Returns short date and short time with seconds

Console.WriteLine("Format Specifier (G):{0:G}",dt);

// Returns Month and Day - M can also be used

Console.WriteLine("Format Specifier (m):{0:m}",dt);

// Returns the date and time in RFC1123 format

// r can also be used

Console.WriteLine("Format Specifier (R):{0:R}",dt);

// Returns Short Time

Console.WriteLine("Format Specifier (t):{0:t}",dt);

// Returns Short Time with Second

Console.WriteLine("Format Specifier (T):{0:T}",dt);

// Returns Year and Month - Y also can be used

Console.WriteLine("Format Specifier (y):{0:y}",dt);

}

}

The final output of the above code will look like Figure 3.4.

Figure 3.4

Arrays

Arrays are not new to C#. They exist in all programming languages such as C, C++ and Java. They enable you to store a list of items of similar data type. For example, to store the age of students you can use an array of type integer. Similarly, if you have to store their names, addresses, and so forth, you can use a string data type.

In C#, arrays are derived from the Array class found in the System namespace. This class contains lot of properties and methods, which you can manipulate for your various programming tasks.

Arrays in C# are declared in the same manner as in Java and C++, and they can be either single or multi-dimensional. Listing 3.5 declares a single dimensional array of type integer and with a dimension of 10. Dimension indicates the number of array elements which you can store in the variable named x.

Listing 3.5

int[] x = new int[10]

Arrays can also be declared as in the code given in listing 3.6:

Listing 3.6

int[] x = {2,3,4,5,6}

The above code snippet stores five integer values. In C#, the index position for the first element is zero. In listing 3.7, an array variable is declared with four values and they are printed using the for loop.

Listing 3.7

using System;

class ArraysDemo

{

public static void Main()

{

int[] x = {10,20,30,40,50};

for(int i = 0; i<=4;i++)

{

Console.WriteLine(x[i]);

}

}

}

Instead of supplying the condition inside the for loop, you can apply the Length property of the Array class to determine the dimensions of an array, as shown in listing 3.8:

Listing 3.8

using System;

class ArraysDemo2

{

public static void Main()

{

int[] x = {10,20,30,40,50};

for(int i = 0; i<x.Length;i++)

{

Console.WriteLine(x[i]);

}

}

}

C# also supports so called multi-dimensional arrays, as shown in the code snippets given below:

// Three dimensional array (Count number of commas and add 1 to it)

int[,,] x

// Two dimensional array

int[,] y

Using Array.Rank

You can programmatically determine the dimension of an array by using the Array.Rank property. Listing 3.9 illustrates the usage of this property in detail:

Listing 3.9

using System;

class ArrayRank

{

int[] SD;

int[,] MD;

int[,,] TD;

ArrayRank()

{

SD = new int[10];

MD = new int[10,20];

TD = new int[10,20,30];

}

void display()

{

Console.WriteLine("SD = {0}",SD.Rank);

Console.WriteLine("MD = {0}",MD.Rank);

Console.WriteLine("TD = {0}",TD.Rank);

}

public static void Main()

{

ArrayRank ar = new ArrayRank ();

ar.display();

}

}

In the above code, a method named display() is created and called by creating an object of the class.

Enumerations

Enumerations are a set of human readable names given instead of the numerical values. They derive from the System.Enum class.

Listing 3.10

case 1:

Console.WriteLine("YES");

break;

case 2:

Console.WriteLine("NO");

break;

Instead of specifying numerical values like 1 and 2 as in the above listing, you can use meaningful constants like ok and cancel. This can be achieved with the help of enumerations. They are defined by using the keyword enum as shown in the following code snippet:

enum Employees

{

YES,

NO

}

In the above code, an enumeration named Employees is defined with two constants YES and NO. Each constant has its own numerical values. By default, the numbering system starts from 0. However, you can change the order as shown in the code snippet given below:

enum Employees

{

YES = 10,

NO = 20

}

Note that the data type for each constant in an enumeration is an integer by default. But you can modify this behavior to byte, long, and so forth as shown in listing 3.11:

Listing 3.11

enum Employees : byte

{

YES,

NO

}

In listing 3.12, an enumeration named Employees is declared with three constants. A method named Display() is then created with the object of our enumerator. Inside the Main() method, an instance of the enumerator is created, and that instance is passed as a parameter to the Display() method. Since I have passed the Counsellors constant, the statements relevant to them will be printed as final output. You may notice from the code that the case clause looks more meaningful and readable than numerical references.

Listing 3.12

using System;

enum Employees

{

Instructors,

Assistants,

Counsellors

}

class EnumDemo

{

public static void Display(Employees e)

{

switch(e)

{

case Employees.Instructors:

Console.WriteLine("You are an Instructor");

break;

case Employees.Assistants:

Console.WriteLine("You are one of the Assistants");

break;

case Employees.Counsellors:

Console.WriteLine("You are a counsellor");

break;

default:break;

}

}

public static void Main(String[] args)

{

Employees emp;

emp = Employees.Counsellors;

Display(emp);

}

}

Summary

In this article, you have learned about different escape characters and format specifiers with the help of complete source codes and screenshots. The article also discussed two important topics -- arrays and enumerations -- with the help of source code.

blog comments powered by Disqus
C# ARTICLES

- Beginning C#
- ASP.NET RedirectPermanent Method using C# an...
- C Programming Language and UNIX Pioneer Pass...
- Using Facebook JavaScript SDK in ASP.NET wit...
- ASP.NET Export to Excel and Word using VB.NE...
- WAV and MP3 Streaming with ASP.Net and C#
- Game Programming using SDL: the File I/O API
- C# and Java Developer Jobs on the Rise
- The Future Evolution of C# and VB.NET
- C# If and Else-if Statements
- How To Use the C# String Replace Method
- 5 Ways to Parse XML in C#
- C# Meets Design Patterns
- Coding a CRC-Generating Algorithm in C
- Cyclic Redundancy Check

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 10 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials