CPAN702 C#



ISDV 165

Lecture 1: C# basics

.NET framework is the heart of .NET technology. It manages and executes applications and web services. .NET framework provides a rich set of class library called FCL ( framework class library). These classes are grouped using the concept of namespaces; the actual code would be located in assembly dll files. The keyword using is used to import a certain class/group of classes into our C# programs.

Some of the namespaces in FCL are:

System: contains basic common classes and data types. Implicitly referenced by C# programs.

System.Data: classes used in to access and manipulate databases

System.Drawing: drawing and graphic classes

System.IO: input and output data and working with files

System.Threading: multithreading classes

System.Window.Forms: used to create GUI

System.Xml: deals with XML

The .NET technology is platform independent. Instead of compiling the .NET applications into machine language directly, they are compiled into MSIL ( Microsoft Intermediate Language) by the CLR ( common language runtime). The Just in Time (JIT) compiles the MSIL into machine specific code. .NET is also language independent. You can develop your application using one or a combination of .NET supported languages. The Common Language Specification (CLS) is part of the .NET that defines the rules and requirements for a language to be .NET compliant.

.NET has many enhanced features such as native XML support, easier database access, better performance, enhanced security and Enhanced state management. The architecture of .NET framework is described in the following figure:

|.NET Framework |

|[pic] | | |

| |

| |

| |

| |

| |

| |

| |

| |

| |

C# syntax:

C# is one of the popular .NET languages that supports structural and object oriented programming. One of the powerful features of C# is the support of accessing memory directly using C++ style pointers. C# is a strongly types language; each object or variable in the program must be declared with a specific type. The syntax of C# is similar to java and C++ syntax.

Comments in C#:

We can use single line comments

//

Or multi-lines comments

/*

*/

Preprocessor directives:

Before the code in compiled, another program called the preprocessor is invoked to prepare the program for the compiler. The preprocessor examines the code for special instructions called processor directive that start with the symbol #.

To define an identifier we use # def directive. To undefined the identifier, we use the #undef directive. To test if an identifier is defined we use #if …#else .. #endif directive.

The #region directive marks an area of text with comments. The directive #endregion points to the end of the marked area. For example:

#define DEBUG

//

# if DEBUG



#else



#endif

The dot operator:

The dot operator is used to access data members and methods of a class. It is also used to restrict a class name to a specific namespace.

Escape sequence:

\t : horizontal tab

\n : newline

\r : carriage return

\” : double quote

\’ : single quote

\\ : backslash

\v : vertical tab

\f : form feed

\0 : null

\b : backspace

\a : alert

Identifier:

An identifier is a name used by the programmer to identify his/her types, methods, variables and so on. It should start with a letter or _. Microsoft recommends using camel notation( initial lower case for variables such as firstName and initial upper case for methods and other identifiers, such as Calculate()). Microsoft does not recommend using the Hungarian notation. For example, iTotal or user_name.

Expressions and Statements:

An expression is a statement that evaluate to a value. For example:

X=10;

The following is a statement but not an expression:

int x;

Variables:

A variable is a storage location with a type. C# requires that all variables to be initialized before they can be used.

The duration of a variable ( lifetime) is the period during which a variable exists in the memory. Variable scope defines where the variable can be referenced in a program.

Variable Scope

A variable scope is the area in the code where the variable is accessible. We can have 3 levels of scopes:

• Global:

Usually defined outside any function or block of code. They are accessible anywhere inside the page.

• Local:

Usually defined in a function and is accessible only within this function or procedure.

• Block level:

Usually defined in a block such as for statement and are accessible only within the specified block.

Constants:

A Constant is a labeled memory location to store constant data. The keywords Const and readnnly are used in C#.NET to declare a constant. Constant data members declared using the const keyword are implicitly static and must be initialized in their declaration. For example:

Public Const TAX=0.015;

Constant data members declared using the readonly keyword can be initialized in their declaration or in the class constructor. Once a constant data member is initialized, its value cannot be changed.

Enumerations:

An enumeration is a set of named constant s called the enumeration list and provide an alternative approach to create constants.

enum myCost :uint

{

x=10;

y=20;

}

The enumeration has a base type which can be any of the integer types. f you leave the base type(uint in the above example), it will be defaulted to int.

To access an enumeration value, we use the dot operator

Console.WriteLine(“the constant x value is {0}”, (uint)myConst.x);

Data types:

C# is a strong typed language. You must declare the type of each variable you declare. Types are divided into two sets: built-in and user-defined (classes).

|Type |Size in byte |.NET type |

|Byte |1 |Byte |

|Char |2 |Char |

|Bool |1 |Boolean |

|Sbyte |1 |SByte |

|Short |2 |Int32 |

|Ushort |2 |UInt32 |

|Int |4 |Int32 |

|Uint |4 |UInt32 |

|Float |4 |Single |

|Double |8 |Double |

|Decimal |16 |Decimal |

|Long |8 |Int64 |

|Ulong |8 |UInt64 |

|String | | |

|Object | | |

.NET maps primitive types to .NET types to ensure objects created in one .NET compliant language are compatible with objects created using any other .NET complaint language.

.NET provides another two types: enum and structs that are discussed later .

Boolean variables in .NET can have the value true or false. Integers cannot be implicitly converted to Booleans.

There are two kinds of conversion between data types. Implicit and explicit. The class Convert in the System namespace is used for explicit conversion.

C# supports both widening and narrowing conversion.

Allowed implicit conversions:

|From |To |

|bool |Object |

|Byte |decimal, double, float, int, uint,long,ulong,object, short, or ushort |

|Sbyte |decimal, double, float, int, long, object, or short |

|Char |decimal, double, float, int, uint, long, ulong, object, ushort |

|Decimal |Object |

|Double |Object |

|Float |double or object |

|Int |decimal, double, float, long, or object |

|Uint |decimal, double, float, long, ulong, or object. |

|Long |decimal, double, float, or object. |

|Ulong |decimal, double, float, or object |

|Short |decimal, double, float, int, long, or object |

|Ushort |decimal, double, float, int, uint, long, ulong, or object. |

Arithmetic Operators:

|Operation |Operator |

|Addition |+ |

|Subtraction |- |

|Multiplication |* |

|Division |/ |

|Modulus |% |

Equity and relational operators:

|Operation |Operator |

|Equality |== |

|Inequality |!= |

|Less than |< |

|Less than or equal to | |

|Greater than or equal to |>= |

Increment/Decrement operators:

|Operation |Example |

|Pre increment |++a |

|Post increment |a++ |

|Pre decrement |--a |

|Post decrement |a-- |

Arithmetic assignment operators:

|Operation |Example |Meaning |

|+= |x+=1 |x=x+1 |

|-= |x-=1 |x=x-1 |

|*= |x*=1 |x=x*1 |

|/= |x/=1 |x=x/1 |

|%= |x%=1 |x=x%1 |

Logical and conditional operators:

|Operation |Operator |

|And |&& |

|Or ||| |

|Logical And |& |

|Logical Or || |

|Exclusive Or |^ |

|Not |! |

Exclusive or return false when both operands are the same, otherwise it return true.

Logical and/or operators are similar to the corresponding and/ or operators except that logical operators always evaluate both operands (no short circuit evaluation).

The Ternary operator (?:):

This operator evaluates a conditional expression and invoke one of two expressions. The general format of this operator is:

Cond-expr ?: expr1:expr2

The operator evaluates the conditional expression and invokes expr1 if the value returned from the conditional expression is true and invokes expr2 otherwise.

Operators precedence:

|Operator |Associatively |

|(),[], . , ++, -- |Left to right |

|++, --, +,-, ! |Right to left |

|*,/,% |Left to right |

|+, - |Left to right |

|= |Left to right |

|==, != |Left to right |

|& |Left to right |

|^ |Left to right |

|| |Left to right |

|&& |Left to right |

||| |Left to right |

|?: |Right to left |

|=,+=,-=,/=,%= |Left to right |

Decision making:

• if statement

if(expression)

{

Statement1;



}

• if … else Statement

if(expression)

{

Statement1;



}

else

{

Statement2;

..

}

• if … else if … else Statement:

if(expression1)

{

Statement1;

}

else if (expression2)

{

Statement2;



}

else

{

statementn;



}

• Switch statement:

switch(expression)

{

case const_expre:

statement1;



break;



default:

statementn;



}

Iteration :

• for Structure

Used when the number of iterations is known in advance. For example

for (int i=0;i ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download