Sie sind auf Seite 1von 48

Diploma Course in Programming with C#.

Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 1

.Net Architecture


CONTENTS

What is .NET Framework?
o CLR, IL & multiplatform
o Multi-language support
o Common API

Enterprise Applications
o J2EE specs and Application Servers
o .NET - Windows OS + .NET Servers

Tools to develop (IDE)
o Visual Studio.NET
o Compare with Java (Netbeans, Eclipse, etc.)


WHAT IS .NET FRAMEWORK?

What is .NET Framework?

Everything needed to build and deploy .NET Applications
Everything - Runtime environment, Classes, APIs, Tools, etc.
The .NET Framework is required to build and run any .NET application and is available
today as a download via Windows Update or directly from the Microsoft .NET Web site
(http://www.microsoft.com/net).
A major and important component of .NET Framework is the runtime environment
What is a runtime environment?
o This is what an application sees!
What is an application?
o Application is synonymous to Program = set of instructions to do something
Runtime environment understands the instructions and executes them


CLR

The runtime environment in .NET Framework is called the Common Language Runtime
(CLR)
A .NET Application is compiled into Intermediate Language (IL), also known as Microsoft
Intermediate Language (MSIL) or managed code.
CLR compiles IL code and executes it.







Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 2

















- .NET applications compile to Intermediate Language
- CLR compiles IL code to native code (JIT compilation) at runtime



WHY NOT USE OSS RUNTIME?

Operating System (OS) provides a runtime environment.
o Not standard across different OSs.
Portability!!!
o Compile once, run anywhere.


MICROSOFTS STRATEGY




















Window OS
for High-end
Servers
(e.g. Data Center)
Hardware
(Servers)
Hardware
(PCs)
Hardware
(Nobile)
Hardware
(Large Server)
Windows OS
for Servers
(e.g. Server)
Windows OS
for PCs
(e.g. Home Ed.)
Windows OS
for Nobile
(e.g. CE)
CLR CLR CLR CLR
Compiled .NET Application
Common
Runtime
Environment
Windows
OS
Different
Devices
Compiled .NET Application in IL
.NET Framework
Common Language Runtime
(CLR)

Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 3

.NET LANGUAGES

Multiple languages (syntaxes) are supported in .NET Framework to build .NET
Applications.
E.g. C#.Net, Visual Basic.Net, ASP.Net etc.
Different language compilers generate IL code.
.NET supports multiple languages.























ASSEMBLY

In .NET, applications (multiple classes etc.) are compiled into a single assembly (usually
taking the form of EXE or DLL).
Every assembly contains metadata that describes it, dependencies on other assemblies, and
version information
Assemblies have the ability to make cross-references to other assemblies with information
stored in metadata


API

In .NET Framework provides a comprehensive a standard class library, called .NET
Framework Class Library, which assist to develop .NET applications in any .NET
language.




.NET Assembly in IL
C#
Compiler
VB
Compiler
C++
Compiler
VJ#
Compiler
C# App VB App C++ App VJ# App
CLR

Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 4

ENTERPRISE APPLICATIONS

Enterprise Applications require a lot of features including:
security,
messaging,
transactions,
logging and etc.


ENTERPRISE APPLICATIONS: .NET APPROACH

No Application Server.
Services/features distributed across various parts of the Operating System.
.NET Framework APIs and services provide many features/services.
In addition to OS, a range of products are available aimed for the enterprise:
Application Center
BizTalk Server
Commerce Server
Content Management Server
Exchange Server
Host Integration Server
SharePoint Portal Server
SQL Server and etc


DEPLOYING .NET APPLICATIONS

Three alternatives exist for deploying a .NET Application:

Run as a Windows Service
Windows Services are system-level processes that run on the machine independent of
the user who is logged in. Typical services include functions of the operating system,
schedulers, virus scanners, database engines, and network components. Using templates
supplied with Visual Studio .NET, it is possible to take a .NET assembly and run it as a
service.

Host through IIS
One way of hosting an assembly is to take advantage of IIS features. IIS allows an
assembly to be deployed and will handle incoming connections, protocols, pooling, and
security via a configuration file located with the assembly.

Use Component Services
Component Services also known as COM+ Services, enable you to include
functionalities such as recycling, state, transactions, method-level security, logging,
impersonation, for hosted components through either an administration tool or the use
of attributes.




Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 5

TOOLS

IDEs play a key role for developer productivity in either platform.
In .NET, Visual Studio.NET is the predominately used IDE.
In Java, a range of tools exists from different vendors: Eclipse, NetBeans, Sun ONE
Studio, etc.


SUMMARY

.NET framework
CLR

.NET has multi-language support.
.NET technology and products from a single vendor: Microsoft





CLR Common Language Runtime.
API Application Programming Interface.
JIT Just in Time.



























Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 6

About C # .Net


.NET FRAMEWORK

The Microsoft .NET Framework is a software framework that can be installed on
computers running Microsoft Windows operating systems. It includes a large library of coded
solutions to common programming problems and a virtual machine that manages the execution of
programs written specifically for the framework. The .NET Framework is a Microsoft offering and
is intended to be used by most new applications created for the Windows platform.


ABOUT C SHARP

C# (pronounced "C Sharp") is a multi-paradigm programming language encompassing
imperative, functional, generic, object-oriented (class-based), and component-oriented
programming disciplines.
It was developed by Microsoft within the .NET initiative and later approved as a standard
by Ecma (ECMA-334) and ISO (ISO/IEC 23270).
C# is one of the programming languages designed for the Common Language
Infrastructure.
C# is intended to be a simple, modern, general-purpose, object-oriented programming
language.
Its development team is led by Anders Hejlsberg, the designer of Borland's Turbo Pascal.
It has an object-oriented syntax based on C++.
It was initially named Cool, which stood for "C-like Object Oriented Language".
However, in July 2000, when Microsoft made the project public, the name of the
programming language was given as C#.
The most recent version of the language is 3.0 which were released in conjunction with the
.NET Framework 3.5 in 2007. The next proposed version, 4.0, is in development.
C# is the programming language that most directly reflects the underlying Common
Language Infrastructure (CLI).
Most of its intrinsic types correspond to value-types implemented by the CLI framework.
However, the language specification does not state the code generation requirements of the
compiler: that is, it does not state that a C# compiler must target a Common Language
Runtime, or generate Common Intermediate Language (CIL), or generate any other specific
format.
Theoretically, a C# compiler could generate machine code like traditional compilers of C++
or FORTRAN. In practice, all existing compiler implementations target CIL.










Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 7

C # VERSIONS

1. C# 2.0
2. C# 3.0
3. C# 4.0

FEATURES

There are no global variables or functions.
C# supports a strict Boolean data type, bool.
Managed memory cannot be explicitly freed.
Multiple inheritances are not supported etc






































Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 8

Introduction to Programming Environments


INTRODUCTION

What is a Computer?
Up until the late 1940s, a Computer was a person who performed calculations.
What about now?

Programs
Programs are sequence of step by step instructions to the computer
Programs, and the data values processed by programs, are called software.


PROGRAMMING LANGUAGES

1. Low-Level Programming Languages
Machine language:
Used by early computers
Executable by machines, almost incomprehensible to humans.
Programming in machine language is very tedious and prone to errors
Ex:
11001010000100101000010101110100
11000101010001110010101000110010

Assembly language:
Mnemonics used for instruction codes and memory locations.
Not directly understandable by machine. They must be translated.
Easier for humans to use and still in use today.
Ex:
ADD X, Y, Reg1
ADD Reg1, Z, Reg2
STORE Reg2 SUM

2. High-Level Programming Languages:

Instructions look more like English and Math.
Generally result in multiple low level commands, for a single high level statement.
Uses syntax resembling combination of mathematical notation and English.
Easy for humans to understand.
Not understandable by machines, must be translated using a compiler or an
interpreter.
Programming tools such as Integrated, Programming Environment (IDE) with a
debugger is available to aid in programming process.






Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 9

PROGRAMMING LANGUAGE TRANSLATION












1. Assemblers:

Translate statement from assembly language to machine language.
Generally use table look-up techniques.

2. Interpreters:

Translate and execute each high-level statement, one at a time.

3. Compilers

Translate the entire high level language program, called the source code, to machine
language and store the result.
Machine language code produced by compilers is called object code.























Source
Program
TransIator
Program
Object
Code

Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 10

Data Types

WHAT ARE DATA TYPES?

A data type is an attribute of a data which tells the computer (and the programmer)
something about the kind of data it is.


VARIABLE DEFINITION

A variable is a named memory location that can be assigned a value. To declare a variable,
you will use a statement like this:
type var-name;

Type specifies the type of variable being declared.
var-name is the name of the variable.


DEFINE AND ASSIGN VALUE TO VARIABLES.

The general form of initialization is shown here:

using System;

class MainClass
{
public static void Main()
{
int x; // declares a variable
int y; // declares another variable

x = 100; // this assigns 100 to x

Console.WriteLine("x contains " + x);
y = x / 2;
Console.Write("y contains x / 2: ");
Console.WriteLine(y);
}
}



DYNAMIC INITIALIZATION

Declare two or more variables using the same declaration statement. Just separate their
names by commas:

int x, y; // both declared using one statement





Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 11

THE C# VALUE TYPES

C# contains two general categories of built-in data types:

Value types:

Type meaning Bool represents true/false values, byte 8-bit unsigned integer, char
Character, decimal Numeric type for financial calculations double Double-precision
floating point float Single-precision floating point int Integer long Long integer sbyte 8-
bit signed integer short short integer uint An unsigned integer ulong An unsigned long
integer ushort An unsigned short integer.

Reference types:

C#'s reference types are defined by classes.




































Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 12

CONVERTING NUMERIC STRINGS TO THEIR INTERNAL REPRESENTATION LITERALS

For the numeric types, the .NET structure names and their C# keyword equivalents are
shown here:


.NET Structure Name C# Name
Decimal decimal
Double double
Single float
Int16 short
Int32 int
Int64 long
UInt16 ushort
UInt32 uint
UInt64 ulong
Byte byte
Sbyte sbyte


The structures are defined inside the System namespace. The fully qualified name for Int32
is System.Int32.


LITERALS

Literals refer to fixed values that are represented in their human-readable form.
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.
A hexadecimal literal must begin with 0x (a zero followed by an x).















Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 13

FAMILY OF INTEGERS

C# defines nine integer types:
char, byte, sbyte, short, ushort, int, uint, long and ulong.

char type is used for representing characters.
The integer structures are:

Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64.

The integer structures also define the following const fields:

MaxValue
MinValue


METHODS SUPPORTED BY THE INTEGER STRUCTURES

Method Meaning
public int CompareTo(object v)
Returns 0 if the values are equal. Returns a
negative value if the invoking object has a lower
value. Returns a positive value if the invoking
object has a greater value.
public override bool Equals(object v) Returns true if equal.
public override int GetHashCode() Returns the hash code.
public TypeCode GetTypeCode()
Returns the TypeCode enumeration value. For
example, for Int32, the type code is
TypeCode.Int32.
public static retType Parse(string str) Parses the string.
public static retType Parse(string
str,IFormatProvider fmtpvdr)
Parse string using the culture-specific information
provided by fmtpvdr.
public static retType Parse(string str,
NumberStyles styles)
Parse string using the style information provided
by styles.
public static retType Parse(string str,
NumberStyles styles,IFormatProvider fmtpvdr)
Parse string using the style information provided
by styles and the culture-specific format
information provided by fmtpvdr.
public override string ToString() Convert value to string.
public string ToString(string format)
Convert value to string as specified by the format
string.
public stringToString(IFormatProvider fmtpvdr)
Returns the string representation of the value of
the invoking object using the culture-specific
information.
public stringToString(string
format,IFormatProvider fmtpvdr)
Returns the string representation of the value of
the invoking object using the culture-specific
information and the format.


Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 14

NAMESPACE

The namespace provides a way to keep one set of names separate from another.
Names declared in one namespace will not conflict with the same names declared in
another.
The namespace System is reserved for items in the .NET Framework class library.
The using keyword simply states that the program is using the names in the given
namespace.


NAMESPACE WITH CLASS DEFINITION

using System;
namespace HelloWorld
{
//<summary>

//Summary description for Class1.

//</summary>
class Class1
{
//<summary>
//The main entry point for the application.
//</summary>
//[STAThread]
static void Main(string[] args)
{
System.Console.WriteLine( "Hello world from C#" );

}
}
}


PARSING STRINGS TO CREATE DATA TYPES

Structure Conversion Method
Decimal static decimal Parse(string str)
Double static double Parse(string str)
Single static float Parse(string str)
Int64 static long Parse(string str)
Int32 static int Parse(string str)
Int16 static short Parse(string str)
UInt64 static ulong Parse(string str)
UInt32 static uint Parse(string str)
UInt16 static ushort Parse(string str)
Byte static byte Parse(string str)
SByte static sbyte Parse(string str)

Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 15

Example-01: bool

using System;
class MainClass
{
public static void Main(string[] args)
{
bool myBool = bool.Parse("True");
Console.WriteLine("-> Value of myBool: {0}", myBool);
}
}


Example-02: int

using System;
class MainClass
{
public static void Main(string[] args)
{
int myInt = int.Parse("8");
Console.WriteLine("-> Value of myInt: {0}", myInt);
}
}


Example-03: char

using System;
class MainClass
{
public static void Main(string[] args)
{
char myChar = char.Parse("w");
Console.WriteLine("-> Value of myChar: {0}\n", myChar);
}
}


THE BOOL TYPE

The bool type represents true/false values.
C# defines the values true and false using the reserved words 'true' and 'false'.
A variable or expression of type bool will be one of these two values.
There is no conversion defined between bool and integer values.


OUTPUT A BOOLEAN VARIABLE WITH CONSOLE.WRITELINE

using System;
class Example
{
public static void Main()
{
Console.WriteLine("10 > 9 is " + (10 > 9));
}
}

Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 16

Operators


THE ASSIGNMENT OPERATOR

It has this general form:
var = expression;

The general form of the shorthand is
var op = expression;

Thus, the arithmetic and logical assignment operators are:

+=
-=
*=
/=
%=
&=
|=
^=


ARITHMETIC OPERATORS


Operator Meaning
+ Addition
- Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement












Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 17

//When / is applied to an integer, any remainder will be truncated.
//For example, 10/3 will equal 3 in integer division.

using System;

class MainClass
{
static void Main(string[] args)
{
int a,b,c,d,e,f;
a = 1;
b = a + 6;
Console.WriteLine(b);
c = b - 3;
Console.WriteLine(c);
d = c * 2;
Console.WriteLine(d);
e = d / 2;
Console.WriteLine(e);
f = e % 2;
Console.WriteLine(f);
}
}



INCREMENT AND DECREMENT ( PREFIX & POSTFIX)

The ++ and the -- are the increment and decrement operators.
The increment operator adds 1 to its operand, and the decrement operator subtracts 1.

x = x + 1;

can be written as

++x; // prefix form

or as

x++; // postfix form


RELATIONAL OPERATORS

Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 18

Arrays


WHAT IS AN ARRAY?

An array is a collection of variables of the same type that are referred to by a common
name.
To declare a one-dimensional array, you will use this general form:

type[] array-name = new type[size];

Array Declaration with initialization, the general form for initializing a one-dimensional
array is shown here:

type[] array-name = { val1, val2, val3, ..., valN };


ARRAY OVERVIEW

An array can be Single-Dimensional, Multidimensional or Jagged.
The default value of numeric array elements are set to zero, and reference elements are set
to null.
A jagged array is an array of arrays, therefore its elements and reference types are
initialized to null.
Arrays are zero indexed: an array with n elements is indexed from 0 to n-1.
Array elements can be of any type, including an array type.
Array types and reference types derived from the abstract base type Array. Since this type
implements IEnumerable and IEnumerable<(Of <(T>)>), you can use foreach iteration on
all arrays in C#.


1. SINGLE DIMENSIONAL ARRAYS

Declare an array of five integers as in the following example:
int[] array = new int[5];
This array contains the elements from array[0] to array[4]. The new operator is used
to create the array and initialize the array elements to their default values. In this
example, all the array elements are initialized to zero.
An array that stores string elements can be declared in the same way. For example:
string[] stringArray = new string[6];










Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 19

SINGLE DIMENSIONAL ARRAY INITIALIZATION

It is possible to initialize an array upon declaration, in which case, the rank specifier is
not needed because it is already supplied by the number of elements in the
initialization list. For example:

int[] array1 = new int[] { 1, 3, 5, 7, 9 };

A string array can be initialized in the same way. The following is a declaration of a
string array where each array element is initialized by a name of a day:

string[] weekDays = new string[] {"Sun","Mon","Tue","Wed","Thu",
"Fri","Sat"};

When you initialize an array upon declaration, you can use the following shortcuts:

int[] array2 = { 1, 3, 5, 7, 9 };

string[] weekDays2 = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};

It is possible to declare an array variable without initialization, but you must use the
new operator when you assign an array to this variable. For example:

int[] array3;
array3 = new int[] { 1, 3, 5, 7, 9 }; // OK
array3 = {1, 3, 5, 7, 9}; // Error


2. VALUE TYPE AND REFERENCE TYPE ARRAYS

Consider the following array declaration:

SomeType[] array4 = new SomeType[10];

The result of this statement depends on whether SomeType is a value type or a
reference type.
If it is a value type, the statement creates an array of 10 instances of the type
SomeType.
If SomeType is a reference type, the statement creates an array of 10 elements, each
of which is initialized to a null reference.


3. MULTIDIMENSIONAL ARRAYS

Arrays can have more than one dimension. For example, the following declaration
creates a two-dimensional array of four rows and two columns:

int[,] array = new int[4, 2];

Also, the following declaration creates an array of three dimensions, 4, 2, and 3:

int[, ,] array1 = new int[4, 2, 3];

Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 20

MULTIDIMENSIONAL ARRAY INITIALIZATION

Initialize the array upon declaration as shown in the following example:

int[,] array2D = new int[,] {{1,2},{3,4},{5,6},{7,8}};
int[, ,] array3D = new int[,,] {{{1,2,3}},{{4,5,6}}};

You can also initialize the array without specifying the rank:

int[,] array4 = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };

If you choose to declare an array variable without initialization, you must use the new
operator to assign an array to the variable. For example:

int[,] array5;
array5 = new int[,] {{1,2},{3,4},{5,6},{7,8}}; // OK
array5 = {{1,2},{3,4},{5,6},{7,8}}; // Error

You can also assign a value to an array element, for example:

array5[2,1] = 25;

The following code example initializes the array variables to default (except for
jagged arrays):

int[,] array6 = new int[10, 10];


4. JAGGED ARRAYS

A jagged array is an array whose elements are arrays.
The elements of a jagged array can be of different dimensions and sizes.
A jagged array is sometimes called an "array of arrays."
The following is a declaration of a single-dimensional array that has three elements,
each of which is a single-dimensional array of integers:

int[][] jaggedArray = new int[3][];

Before you can use jaggedArray, its elements must be initialized. You can initialize
the elements like this:

jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];

Each of the elements is a single-dimensional array of integers.
The first element is an array of 5 integers, the second is an array of 4 integers, and the
third is an array of 2 integers.
It is also possible to use initializers to fill the array elements with values, in which
case you do not need the array size. For example:


Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 21

jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };

You can also initialize the array upon declaration like this:

int[][] jaggedArray2 = new int[][]
{
new int[] {1,3,5,7,9},
new int[] {0,2,4,6},
new int[] {11,22}
};

You can use the following shorthand form. Notice that you cannot omit the new
operator from the elements initialization because there is no default initialization for
the elements:

int[][] jaggedArray3 = {
new int[] {1,3,5,7,9},
new int[] {0,2,4,6},
new int[] {11,22}
};

A jagged array is an array of arrays, and therefore its elements are reference types and
are initialized to null.
You can access individual array elements like these examples:

// Assign 77 to the second element ([1]) of the first array
([0]):
jaggedArray3[0][1] = 77;

// Assign 88 to the second element ([1]) of the third array
([2]):
jaggedArray3[2][1] = 88;

It is possible to mix jagged and multidimensional arrays. The following is a
declaration and initialization of a single-dimensional jagged array that contains two-
dimensional array elements of different sizes:

int[][,] jaggedArray4 = new int[3][,]
{
new int[,] { {1,3}, {5,7} },
new int[,] { {0,2}, {4,6}, {8,10} },
new int[,] { {11,22}, {99,88}, {0,9} }
};

You can access individual elements as shown in this example, which displays the
value of the element [1,0] of the first array (value 5):

System.Console.Write("{0}", jaggedArray4[0][1, 0]);

The method Length returns the number of arrays contained in the jagged array. For
example, assuming you have declared the previous array, this line:

System.Console.WriteLine(jaggedArray4.Length);

Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 22

USING FOREACH WITH ARRAYS

C# also provides the foreach statement. This statement provides a simple, clean way to
iterate through the elements of an array. For example, the following code creates an array
called numbers and iterates through it with the foreach statement:

int[] numbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };
foreach (int i in numbers)
{
System.Console.WriteLine(i);
}

With multidimensional arrays, you can use the same method to iterate through the elements,
for example:

int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
foreach (int i in numbers2D)
{
System.Console.Write("{0} ", i);
}

However, with multidimensional arrays, using a nested for loop gives you more control over
the array elements.



PASSING ARRAYS AS PARAMETERS

Arrays may be passed to methods as parameters. As arrays are reference types, the method
can change the value of the elements.
Passing single-dimensional arrays as parameters
You can pass an initialized single-dimensional array to a method. For example:

PrintArray(theArray);

The method called in the line above could be defined as:

void PrintArray(int[]arr)
{
//method code
}

You can also initialize and pass a new array in one step. For example:

PrintArray(new int[] { 1, 3, 5, 7, 9 });








Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 23


PASSING MULTIDIMENSIONAL ARRAYS AS PARAMETERS

You can pass an initialized multidimensional array to a method. For example, if theArray
is a two dimensional array:

PrintArray(theArray);

The method called in the line above could be defined as:

void PrintArray(int[,]arr)
{
//method code
}

You can also initialize and pass a new array in one step. For example:

PrintArray(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } });

































Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 24

Statements


THE IF STATEMENT

You can selectively execute part of a program through the if statement. Its simplest form is
shown here:

if(condition)
statement;

Condition is a Boolean (that is, true or false) expression. If condition is true, then the statement
is executed. If condition is false, then the statement is bypassed. The complete form of the if
statement is:

if(condition)
statement;
else
statement;

The general form of the if using blocks of statements is:

if(condition)
{
statement sequence;
}
else
{
statement sequence;
}


//if-else-if ladder. It looks like this:

if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
.
else
statement;










Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 25

THE SWITCH STATEMENT

The switch expression must be of an integer type, such as char, byte, short, or int, or of type
string.
The default statement sequence is executed if no case constant matches the expression.
The default is optional.
If default is not present, no action takes place if all matches fail.
When a match is found, the statements associated with that case are executed until the break
is encountered.

The general form of the switch statement is:

switch(expression)
{
case constant1:
statement sequence;
break;
case constant2:
statement sequence;
break;
case constant3:
statement sequence;
break;
.
.
.
default:
statement sequence;
break;
}


USE GOTO WITH A SWITCH

The goto is C#'s unconditional jump statement.
When encountered, program flow jumps to the location specified by the goto.
The goto requires a label for operation.
A label is a valid C# identifier followed by a colon.
















Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 26

Example-01:

using System;
class SwitchGoto
{
public static void Main()
{
for (int i = 1; i < 5; i++)
{
switch (i)
{
case 1:
Console.WriteLine("In case 1");
goto case 3;
case 2:
Console.WriteLine("In case 2");
goto case 1;
case 3:
Console.WriteLine("In case 3");
goto default;
default:
Console.WriteLine("In default");
break;
}
Console.WriteLine();
}
}
}



























Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 27

Loops


THE FOR LOOP

for loop you can repeatedly execute a sequence of code by creating a loop. The general form
of the for loop for repeating a single statement is:

for(initialization; condition; iteration)
statement;

//For repeating a block, the general form is

for(initialization; condition; iteration)
{
statement sequence
}


Example-01:

using System;
class MainClass
{
public static void Main()
{
int count;
for (count = 0; count < 5; count = count + 1)
Console.WriteLine("This is count: " + count);
Console.WriteLine("Done!");
}
}


THE FOREACH LOOP

The foreach loop is used to cycle through the elements of a collection. The general form of
foreach is shown here:

foreach(type var-name in collection)
statement;



THE DO WHILE LOOP

Do while loop A do-while loop will always execute at least once. The general form of the do-
while loop is:

do
{
statements;
}while(condition);


Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 28

Hello World My First Program

using System;
// A "Hello World!" program in C#
namespace HelloWorld
{
class Hello
{
static void Main()
{
System.Console.WriteLine("Hello World!");
}
}
}


COMMENTS

// A "Hello World!" program in C#

The characters // convert the rest of the line to a comment. You can also comment a block of
text by enclosing it between the /* and */ characters, for example:


THE MAIN METHOD

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

The statement, System.Console.WriteLine("Hello World!"); uses the WriteLine method,
one of the output methods of the Console class in the run-time 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.

If you include the using System; directive at the beginning of the program, you can directly
use the System classes and methods without fully qualifying them.

For example, you can call Console.WriteLine instead, without specifying
System.Console.Writeline:













Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 29

COMPILATION AND EXECUTION

You can compile the "Hello World!" program either by creating a project in the Visual
Studio IDE, or by using the command line. Use the Visual Studio Command Prompt or invoke
vsvars32.bat to put the Visual C# tool set on the path in your command prompt.
To compile the program from the command line:

Create the source file by using any text editor and save it using a name such as Hello.cs. (
C# source code files use the extension .cs).

To invoke the compiler, enter the command:
csc Hello.cs

If your program does not contain any compilation errors, a Hello.exe file will be created.
To run the program, enter the command:
Hello


SAMPLE COMMAND LINES

1. Compiles File.cs producing File.exe:
csc File.cs

2. Compiles File.cs producing File.dll:
csc /target:library File.cs

3. Compiles File.cs and creates My.exe:
csc /out:My.exe File.cs

4. Compiles all the C# files in the current directory, with optimizations on and defines the
DEBUG symbol. The output is File2.exe:
csc /define:DEBUG /optimize /out:File2.exe *.cs
5. Compiles all the C# files in the current directory producing a debug version of File2.dll. No
logo and no warnings are displayed:
csc /target:library /out:File2.dll /warn:0 /nologo /debug *.cs

6. Compiles all the C# files in the current directory to Something.xyz (a DLL):
csc /target:library /out:Something.xyz *.cs













Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 30

Introduction to Object Oriented programming (OOP)


OBJECT-ORIENTED THE MIRRORS REAL WORLD

Consider real world situations involving things (objects) and actions (procedures).
We consider the object first, and then what action is appropriate.
For example, we select an object (apple) and then the action (eats, peel, sell, move, etc).
We do not think of an action (move) and then look around for an object.


INTRODUCTION

Object-Oriented Programming (OOP) is a replacement for conventional programming.
It is a new way of organizing and developing programs and has nothing to do with any
particular language.
However, not all languages are suitable to implement the OOP concepts easily.
There is a good reason for this transformation. OOP offers several benefits, such as easy
code maintenance, extensibility, and code reuse, not found in procedural programming
languages.
Languages that support OOP features are Smalltalk, Objective C, C++, Ada and Object
Pascal and VB.net etc.
C++ was created as an extension of C to support OOP.
Java, one of the most popular languages on the planet, is also an OOP language.


THE BENEFITS OF OOPS

1. Extensibility:

OOP naturally supports extensibility. Having a class with certain functionality, you can
quickly extend that class to create a different class with extended functionality.

2. Code Reuse:

Since functionality is encapsulated into a class and each class is an independent entity,
providing a library is very easy. In fact, programmers of any .NET Framework language
can and should use the .NET Framework class library, an extensive library that provides
rich functionality. Better still, you can extend the functionality of the class library to
provide classes that suit your needs.










Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 31

CLASSES

Classes are the main focus in OOP.
Simply put, a class is a data type that provides some functionality.
A class is a template that defines the form of an object.
A class specifies both the data and the code that will operate on that data.
Objects are instances of a class.
The methods and variables that constitute a class are called members of the class.


THE GENERAL FORM OF A CLASS

// A class is created by use of the keyword class.

class classname
{
// declare instance variables
access type var1;
access type var2;
// ...
access type varN;
// declare methods
access ret-type method1(parameters)
{
// body of methodu160 ?
}
access ret-type method2(parameters)
{
// body of method
}
// ...
access ret-type methodN(parameters)
{
// body of method
}
}


The general form for declaring an instance variable is shown here:

access type varN;

access specifies the access,
type specifies the type of variable, and var-name is the variable's name.
To access these variables, you will use the dot (.) operator.
The dot operator links the name of an object with the name of a member.
The general form of the dot operator is shown here:

object.member;

You can use the dot operator to access both instance variables and methods.




Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 32

// A Simple Class showing class definition syntax

class MyClass
{
int simpleValue = 0;
}


CONSTRUCTOR

constructor to class A constructor initializes an object when it is created.
A constructor has the same name as its class.
A constructor is syntactically similar to a method.
Constructors have no explicit return type.
The general form of constructor is shown here:

access class-name()
{
// constructor code
}


DESTRUCTOR

A destructor method called just prior to an object's final destruction by the garbage
collector.
A destructor can be used to ensure that an object terminates cleanly.
Destructors have this general form:

~class-name()
{
// destruction code
}




















Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 33

ACCESS SPECIFIERS

C#'s Access Specifies An access specifies determines how other parts of a program can
access a class member.
Member access is controlled by four access specifies:
o Public.
o Private.
o Protected.
o Internal.

Public member can be accessed by any other code in your program.
Main() is declared as public because it will be called by code outside of its class (the
operating system).
Private member can be accessed only by other members of its class.
A Protected member is public within a class hierarchy, but private outside that hierarchy.
A Protected member is created by using the protected access modifier.
The internal modifier declares that a member is known throughout all files in an assembly,
but unknown outside that assembly.
The protected internal access level can be given only to class members.
A member declared with protected internal access is accessible within its own assembly or
to derived types.





























Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 34

OOP Concepts


KEY CONCEPTS OF OBJECT ORIENTATION

1. Abstraction.
2. Encapsulation.
3. Polymorphism.
4. Inheritance.


ABSTRACTION

Abstraction is the ability to generalize an object as a data type that has a specific set of
characteristics and is able to perform a set of actions.
Object-oriented languages provide abstraction via classes. Classes define the properties and
methods of an object type.

Examples:

You can create an abstraction of a dog with characteristics, such as color, height, and weight,
and actions such as run and bite.

The characteristics are called properties, and the actions are called methods.
A Recordset object is an abstract representation of a set of data.
Classes are blueprints for Object.
Objects are instance of classes.

// C# Example of Class:

public class Draw
{
// Class code.
}


OBJECT REFERENCES

When we work with an object we are using a reference to that object. On the other hand, when
we are working with simple data types such as Integer, we are working with the actual value
rather than a reference.

When we create a new object using the New keyword, we store a reference to that object in
a variable. For instance:

Draw MyDraw = new Draw;

This code creates a new instance of Draw.
We gain access to this new object via the MyDraw variable. This variable holds a reference
to the object.

Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 35

Now we have a second variable, which also has a reference to that same object.
We can use either variable interchangeably, since they both reference the exact same object.
The thing we need to remember is that the variable we have is not the object itself but,
rather, is just a reference or pointer to the object itself.


EARLY BINDING

Early binding means that our code directly interacts with the object, by directly calling its
methods.
Since the compiler knows the object's data type ahead of time, it can directly compile code
to invoke the methods on the object.
Early binding also allows the IDE to use IntelliSense to aid our development efforts;
it allows the compiler to ensure that we are referencing methods that do exist and that we
are providing the proper parameter values.


LATE BINDING

Late binding means that our code interacts with an object dynamically at run-time.
This provides a great deal of flexibility since our code literally doesn't care what type of
object it is interacting with as long as the object supports the methods we want to call.
Because the type of the object isn't known by the IDE or compiler, neither IntelliSense nor
compile-time syntax checking is possible but we get unprecedented flexibility in exchange.
If we enable strict type checking by using Option Strict On at the top of our code modules,
then the IDE and compiler will enforce early binding behavior.
By default, Option Strict is turned off and so we have easy access to the use of late binding
within our code.


INHERITANCE

In the real world there are many objects that can be specialized.
In OOP, a parent class can inherit its behavior and state to children classes.
This concept was developed to manage generalization and specialization in OOP and is
represented by a is-a relationship.
The following OO terms are commonly used names given to parent and child classes in
OOP:

o Superclass: Parent class.
o Subclass: Child class.
o Base class: Parent class.
o Derived class: Child class

The most common real world sample to explain inheritance is the geometric shapes object
model. Squares, circles, triangles, rectangles, pentagons, hexagons, and octagons are
geometric shapes.



Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 36

The following figure shows a sample set of geometric figures:
























The concept of generalization in OOP means that an object encapsulates common state an
behavior for a category of objects.
The general object in this sample is the geometric shape.
Most geometric shapes have area, perimeter, and color.
The concept of specialization in OOP means that an object can inherit the common state and
behavior of a generic object; however, each object needs to define its own special and
particular state an behavior.
In Figure 1, each shape has its own color. Each shape has also particular formulas to
calculate its area and perimeter.
Inheritance makes code elegant and less repetitive.
If we know that all shapes have color, should we program a color attribute for each shape?
The answer is no! Would it be a better idea to create a shape class that has a color attribute
and to make all the specialized shapes to inherit the color attribute? The answer is yes!
An object model for this sample could have a shape parent class and a derived class for each
specific shape.
The following UML class diagram shows the set of classes needed to model the geometric
shapes sample. Observe the field, properties, and methods for each class:







Figure 1

Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 37




































Figure 2. The Shape class is the parent class.
Square, Rectangle, and Circle are derived classes that inherit from Shape. The triangle-
connector in the diagram represents an is-a relationship.
The .NET framework has many base classes. Everything is derived from System.Object.
You can create almost anything you imagine using the built-in functionality provided in the
.NET Framework Class Library.
To create a derived class in C#, the class declaration should be done as:

class child: parent

To create a derived class in VB.NET, the class declaration should be done as:

Class child
Inherits parent
End Class
Figure 2

Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 38

MULTIPLE INHERITANCES

Multiple inheritances is the possibility that a child class can have multiple parents.
Human beings have always two parents, so a child will have characteristics from both
parents.
In OOP, multiple inheritances might become difficult to handle because it allows ambiguity
for the compiler.
There are programming languages such as C++ that allow multiple inheritances; however,
other programming languages such as Java and the .NET Framework languages do not
allow multiple inheritances.
Multiple inheritances can be emulated in .NET using Multiple Interface Inheritance.








































Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 39

Structured Query Language (SQL)


WHAT IS SQL?

SQL stands for Structured Query Language.
SQL lets you access and manipulate databases.
SQL is an ANSI (American National Standards Institute) standard.


WHAT CAN SQL DO?

SQL can execute queries against a database.
SQL can retrieve data from a database.
SQL can insert records in a database.
SQL can update records in a database.
SQL can delete records from a database
SQL can create new databases.
SQL can create new tables in a database.
SQL can create stored procedures in a database.
SQL can create views in a database.
SQL can set permissions on tables, procedures, and views.


SQL IS A STANDARD BUT

Although SQL is an ANSI (American National Standards Institute) standard, there are many
different versions of the SQL language.
However, to be compliant with the ANSI standard, they all support at least the major
commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar
manner.
Note: Most of the SQL database programs also have their own proprietary extensions in
addition to the SQL standard!



RDBMS

RDBMS stands for Relational Database Management System.
RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server,
IBM DB2, Oracle, MySQL, and Microsoft Access.
The data in RDBMS is stored in database objects called tables.
A table is a collection of related data entries and it consists of columns and rows.






Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 40

THE SQL SELECT STATEMENT

The SELECT statement is used to select data from a database.
The result is stored in a result table, called the result-set.

SQL SELECT Syntax

SELECT column_name(s)
FROM table_name

Or

SELECT * FROM table_name


THE SQL SELECT DISTINCT STATEMENT

In a table, some of the columns may contain duplicate values. This is not a problem,
however, sometimes you will want to list only the different (distinct) values in a table.
The DISTINCT keyword can be used to return only distinct (different) values.

SQL SELECT DISTINCT Syntax

SELECT DISTINCT column_name(s)
FROM table_name


THE WHERE CLAUSE

The WHERE clause is used to extract only those records that fulfill a specified criterion.

SQL WHERE Syntax

SELECT column_name(s)
FROM table_name
WHERE column_name operator value















Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 41

OPERATORS ALLOWED IN THE WHERE CLAUSE


Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN
If you know the exact value you want to
return for at least one of the columns




THE AND & OR OPERATORS

The AND operator displays a record if both the first condition and the second condition is
true.
The OR operator displays a record if either the first condition or the second condition is
true.


COMBINING AND & OR

You can also combine AND and OR (use parenthesis to form complex expressions).
Now we want to select only the persons with the last name equal to "Svendson" AND the
first name equal to "Tove" OR to "Ola":
We use the following SELECT statement:

SQL AND & OR Syntax

SELECT *
FROM Persons
WHERE LastName = 'Svendson' AND (FirstName = 'Tove' OR FirstName = 'Ola')








Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 42

THE ORDER BY KEYWORD

The ORDER BY keyword is used to sort the result-set by a specified column.
The ORDER BY keyword sort the records in ascending order by default.
If you want to sort the records in a descending order, you can use the DESC keyword.

SQL ORDER BY Syntax

SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC | DESC


THE INSERT INTO STATEMENT

The INSERT INTO statement is used to insert a new row in a table.
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their
values:

SQL INSERT INTO Syntax

INSERT INTO table_name
VALUES (value1, value2, value3,...)

The second form specifies both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)



THE UPDATE STATEMENT

The UPDATE statement is used to update existing records in a table.

SQL UPDATE Syntax

UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column = some_value

Note: The WHERE clause specifies which record or records that should be updated. If you
omit the WHERE clause, all records will be updated!






Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 43

THE DELETE STATEMENT

The DELETE statement is used to delete rows in a table.

SQL DELETE Syntax

DELETE FROM table_name
WHERE some_column = some_value

Note: The WHERE clause specifies which record or records that should be deleted. If you
omit the WHERE clause, all records will be deleted!


DELETE ALL ROWS

It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:

SQL DELETE Syntax

DELETE FROM table_name

Or

DELETE * FROM table_name

Note: Be very careful when deleting records. You cannot undo this statement!


THE LIKE OPERATOR

The LIKE operator is used to search for a specified pattern in a column.

SQL LIKE Syntax

SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern


THE CREATE DATABASE STATEMENT

The CREATE DATABASE statement is used to create a database.

SQL CREATE DATABASE Syntax

CREATE DATABASE database_name




Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 44

THE CREATE TABLE STATEMENT

The CREATE TABLE statement is used to create a table in a database.

SQL CREATE TABLE Syntax

CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)


THE ALTER TABLE STATEMENT

The ALTER TABLE statement is used to add, delete, or modify columns in an existing
table.

SQL ALTER TABLE Syntax

To add a column in a table, use the following

ALTER TABLE table_name
ADD column_name datatype

To delete a column in a table, use the following syntax (notice that some database systems
don't allow deleting a column):

ALTER TABLE table_name
DROP COLUMN column_name

To change the data type of a column in a table, use the following syntax:

ALTER TABLE table_name
ALTER COLUMN column_name datatype














Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 45

SQL CONSTRAINTS

Constraints are used to limit the type of data that can go into a table.
Constraints can be specified when a table is created (with the CREATE TABLE statement)
or after the table is created (with the ALTER TABLE statement).
We will focus on the following constraints:

o NOT NULL:

The NOT NULL constraint enforces a column to NOT accept NULL values.
The NOT NULL constraint enforces a field to always contain a value. This
means that you cannot insert a new record, or update a record without
adding a value to this field.

o UNIQUE:

The UNIQUE constraint uniquely identifies each record in a database table.
The UNIQUE and PRIMARY KEY constraints both provide a guarantee for
uniqueness for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint
defined on it.
Note: that you can have many UNIQUE constraints per table, but only one
PRIMARY KEY constraint per table.

Example : SQL Server / Oracle / MS Access:

CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)


To allow naming of a UNIQUE constraint, and for defining a UNIQUE
constraint on multiple columns, use the following SQL syntax:

CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
)


Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 46

o PRIMARY KEY:

The PRIMARY KEY constraint uniquely identifies each record in a database
table.
Primary keys must contain unique values.
A primary key column cannot contain NULL values.
Each table should have a primary key, and each table can have only one
primary key.

CREATE TABLE Persons
(
P_Id int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

To allow naming of a PRIMARY KEY constraint, and for defining a
PRIMARY KEY constraint on multiple columns, use the following SQL
syntax:

CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)

o FOREIGN KEY:

A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
The FOREIGN KEY constraint is used to prevent actions that would destroy
link between tables.
The FOREIGN KEY constraint also prevents that invalid data is inserted into
the foreign key column, because it has to be one of the values contained in
the table it points to.

CREATE TABLE Orders
(
O_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int FOREIGN KEY REFERENCES Persons(P_Id)
)

o CHECK
o DEFAULT

Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 47

MICROSOFT ACCESS DATA TYPES

Data type Description Storage
Text
Use for text or combinations of text and numbers. 255 characters
maximum

Memo
Memo is used for larger amounts of text. Stores up to 65,536 characters.
Note: You cannot sort a memo field. However, they are searchable

Byte Allows whole numbers from 0 to 255 1 byte
Integer Allows whole numbers between -32,768 and 32,767 2 bytes
Long Allows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytes
Single Single precision floating-point. Will handle most decimals 4 bytes
Double Double precision floating-point. Will handle most decimals 8 bytes
Currency
Use for currency. Holds up to 15 digits of whole dollars, plus 4 decimal
places. Tip: You can choose which country's currency to use
8 bytes
AutoNumber
AutoNumber fields automatically give each record its own number,
usually starting at 1
4 bytes
Date/Time Use for dates and times 8 bytes
Yes/No
A logical field can be displayed as Yes/No, True/False, or On/Off. In code,
use the constants True and False (equivalent to -1 and 0). Note: Null
values are not allowed in Yes/No fields
1 bit
Ole Object Can store pictures, audio, video, or other BLOBs (Binary Large OBjects)
up to
1GB
Hyperlink Contain links to other files, including web pages
Lookup
Wizard
Let you type a list of options, which can then be chosen from a drop-down
list
4 bytes




Diploma Course in Programming with C#.Net
Conducted by LAVTC Ratmalana(Prepared by Suranga Fernando) 48

SQL SERVER DATA TYPES : CHARACTER STRINGS


Data type Description Storage
char(n)
Fixed-length character string. Maximum 8,000
characters
n
varchar(n)
Variable-length character string. Maximum
8,000 characters

varchar(max)
Variable-length character string. Maximum
1,073,741,824 characters

text
Variable-length character string. Maximum 2GB
of text data

int
Allows whole numbers between -2,147,483,648
and 2,147,483,647
4 bytes
float(n)
Floating precision number data from -1.79E +
308 to 1.79E + 308.The n parameter indicates
whether the field should hold 4 or 8 bytes.
float(24) holds a 4-byte field and float(53) holds
an 8-byte field. Default value of n is 53.
4 or 8 bytes
datetime
From January 1, 1753 to December 31, 9999
with an accuracy of 3.33 milliseconds

Das könnte Ihnen auch gefallen