Saturday, November 05, 2005

C# Self Tutor (Chapter 2)

C# COMPILER AND EDITORS:

.NET SDK Beta 1 release of Microsoft’s new platform, .NET, incorporated with C# command line compiler. You must have to install .NET SDK to run a C# program. Once you install .NET SDK you can write your C# program in any text editors including notepad, WordPad or visual studio.

FIRST C# PROGRAM

/* welcome to the world of C# programming */

Class ebony

{

Static void main ()

{

System.console.writeline (“heavens”);

}

}

To compile the above program from the command line:

Create the source file using any text editor such as notepad etc. save it using a name such as ebony.cs. C# source code files usually have the extension as .csTo invoke the compiler, enter the command

csc ebony.cs

If your program does not contain any compilation errors, a ebony.exe file will be created.

To run the program enter the command:

C:\csharp>ebony

output of the above program is:

heavens

Alternative way of coding the above program is to define using directive at the top of the program as shown below:

/* welcome to the world of C# programming */

Using system; // using directives

Class ebony

{

Static void main ()

{

console.writeline (“heavens”);

}

}

The C# program must contain a main method, in which control starts and ends. The main method is where you create objects and execute other methods.

The main method is a static method that resides inside a class or a struct.

There are three methods to declare the main method:

  • it can return a void

Static void main ()

{

…….

}

  • it can also return an int

Static int main ()

{

……….

return 0;

}

  • it can also take arguments

static int main(string[] args)

{
………..

return 0;

}

C# programs generally use the input/output services provided by run-time library of the .NET Framework. The statement:

System.console.writeline (“heavens”);

Uses the writeline method, one of the output methods of the console class in the runtime library. It displays its string parameter on the standard output stream followed by a new line. Other console methods are used for different input and output operations.

Another example:

Class ebony

{

Static void main ()

{
system.console.writeline (“100{0}, {1}”, 100,200);

}

}

Output

100 100, 200

Here the {0} is replaced with 100 and {1} is replaced with 200. the comma (,) separates the two numbers. Thus {0} means the first number and {1} means the second. C# likes to count from zero and not one.

Another example:

Class ebony

{

Static void main ()

{
int k,a;

k=09;

a=14;

system.console.writeline (“{0}{1}”, a,k);

}

}

Output:

1409

COMPILING AND RUNNING C#:

To compile the program, create a source file by using any text editor and save it with the extension .cs.

For example if the name if the C# source code file is ebony.cs then the proper command would be

Csc ebony.cs /t:exe /out:ebony.cs

As /t:exe and /out:ebony.cs are the default compiler settings these can be left out, therefore the simplest command is:

Csc ebony.cs

/target (Specifies the output file format)

/target:exe creates an .exe file

/target:library creates a code(.dll) file

/target:module creates a module

/target:winexe creates a window program that provides user interface from either from either frame work library or with Win32 API’s

/main compiler option lets you specify which class contains the Main method, in case your code has more than one class Main method

TYPES

C#. supports two kinds of types : value types and reference types.

Value types include simple types include simple types (eg char, int , float), enum

types, and struct types.

Reference types include class types, interface types, delegate types and array types.

The variables of the value types directly contain their data, where as variable of the reference types store references to objects. The new operator is used when a reference is declared and then will immediately point to something.

C# provides two predefined reference-types object and string. All the other reference types tend to be class defined by the user. However all inherit from system.object. this system.object class has ToString() method, which simply returns a class name or value depending on what is being applied to.

There are predefined data types likes byte, short, int, long which represent 8-bit, 16-bit, 32-bit and 64 bit signed integer data type. Byte, ushort, unit, ulong represents 8-bit, 16-bit, 32bit and 64-bit unsigned integer data type respectively. Float and double type represents single and double precision floating data type. Decimal data represents 128 bit data type and can have 28 significant digits. The char represents character data types. The bool data type indicates true of false. The type bool is an alias for system.boolean.

DATA TYPE CONVERSION:

C# supports two types of conversion. Implicit and explicit conversions.

Implicit conversions are direct conversion. For example:

int ival=34;

long lval=intvalue;

explicit conversions include type casting, conversion. For example:

long lval=1409

int ival=(int)lval;

CHECKED AND UNCHECKED OPERATOR:

The checked and unchecked operators are used to control the arithmetic overflow for integral-type arithmetic operations and conversions.

using system;

class ebony

{

Public static void main ()

{
int num=400; // 110010000

unchecked

{

Byte c= (byte) num; //overflow never detected

System.console.writeline (“the value of b :{ 0}”, c);

}

}

}

Output

The value of b: 144

In an unchecked context, the result is truncated by discarding any high-order bits that do not fit in the destination type. The binary equivalent of 144 is 10010000. Because of this overflow exception is not thrown. If unchecked will be changed to check an unhandled exception will be thrown.

VARIABLES AND PARAMETERS ref & out

A variable has a storage location and a specific type. This specific type defines what can be stored in that variable. A field is also a variable and is a usually associated with a lass or an object.

Program A

using system

class ebony

{

Public static void main ()

{

int a=3,b=a*4;

console.writeline (“a={0},b={1}”,a,b);

}

}

Output

A=3, b=12

The local variables a and b are declared and initialized with an initial value. Formal parameter declaration also defines variables. There are four kinds of parameters:

Value parameters, reference parameters, out parameters and parameter arrays.

A value parameter is usually initially before passing this variable as an argument into a method. Any change in the value of the parameter in the method has no effect in the corresponding variable, because the parameter is initialized by copying the value of the corresponding argument.

Program B:

using system;

class ebony

{

Static void display (int x)

{

x=x+20;

console.writeline (“the value inside method :{ 0}”, x);

}

Public static void main ()

{
int a=3,b=a*3;

Console.writeline (“before call of the method a={0},b={1}”,a,b);

Console.writeline (“after call of the method a={0},b={1}”a,b);

}

}

Output:

before call of the method a=3, b=9

the value inside method: 23

after call of the method a=3, b=9

This example shows a method display that has a value parameter named x. the last line prints a=3 and b=9, even though the value parameter is modified.

A reference parameter is declared with the keyword ref. A reference parameter does not declare a new storage location. Any change in the reference parameter directly changes the corresponding argument.

The ref keyword is required both in the method declaration and the method invocation. The variable is initialized before used in the method as a reference parameter.

NUMERIC FORMATTING:

Numeric types can be formatted using the standard format characters. The console.writeline () use the format character to format the numeric type as specified. Different format characters and their description are as follows:

Format character description

C or c currency format

D or d decimal format

E or e exponential format

F or f fixed point format

G or g general format

N or n number format

P or p percent format

R or r round trip format

X or x hexadecimal format

STRING MANUPULATION:

A string represents a series of characters. Once the instance of a string is created it cam not be changed. The string class provides various functions to manipulate a string and these functions generate a new string. Different functions are like copy, insert, join, concat, split, substring etc.

Using system;

Using system.text;

Class ebony

{
public static void main()

{

Stringbuilder sb=new stringbuilder (“shoppers’”);

Sb=sb.append (“stop”);

Console.writeline (sb);

Sb.insert (5,” “);

Sb=sb.insert (8,” “);

Console.writeline (sb);

Console.writeline (sb.length);

Console.writeline (sb.append (“ “+”237/10-359/2”));

Console.writeline (sb.length);

}

}

The stringbuilder classes us used to represent a string which can be manipulated using different methods like append, insert and remove. The new string can still be references using the same instance. The new instance of the stringbuilder class sb is initially assigned using the constructor. The subsequently the instance of the stringbuilder is modified using the append method of the stringbuilder class. The length property can be used to get or set the length of the instance of the string.