Vous êtes sur la page 1sur 82

C Sharp Programming – Day 1

ER/CORP/CRS/LA06/003 1
Course Objectives
• To introduce the participants to C# programming and object oriented features
of C#
• To understand the component oriented features of C# like indexers, properties,
attributes and illustrate their usage in programs
• To introduce development of Assembly
• To introduce Windows programming and delegate based event handling in C#
• To understand Exception handling techniques in C#
• To introduce Multithreading in C#
• To introduce to Reflection
• To introduce File Handling in C#
• To introduce Parsing
• To introduce concept of Remoting through C# programs
• To introduce Windows Services
• To introduce Application Deployment

Copyright © 2005, 2 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 2
Day Wise Plan
• Day1
− Recap of OO
- Data Types
- Class & Object
- Inheritance
- Namespace
- Structure

• Day 2
− Interface
− Assembly
− Property
− Indexer
− Collection
− Preprocessor Directives

Copyright © 2005, 3 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 3
Day Wise Plan
• Day 3
− GUI
− Delegates
− Unsafe Code
− Exception Handling
− Debugging
• Day 4
− Threading
− Reflection
− Serialization
− File Handling
• Day 5
− Parsing
− Remoting
− Windows Services
− Deployment

• Day 6 and Day 7 - Project

Copyright © 2005, 4 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 4
References
• Tom Archer,” Inside C# “ ,WP Publications
• Peter Drayton, Ben Albahari and Ted Neward, “C# in a nutshell” , O’reily
Publications
• Microsoft Corporation , “Microsoft C# Language Specifications “, Microsoft
Press, New York.
• Microsoft Corporation, “Developing Windows –based Applications with
Microsoft VB .Net and Visual C# .NET”,PHI Publications
• Robinson, Nagel, Glynn, Skinner, Watson and Evjen, “Professional C#”, Wiley
Publications
• Andrew Troelsen, “C# and the .NET Platform “, Apress, CA,USA
• http://www.c-sharpcorner.com/
• http://gotdotnet.com/

Copyright © 2005, 5 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 5
Session Plan
• Recap of OO
• Classes and Objects
• Basic Data Types and Control structures,
• Data Members and Methods of a Class (Creation of objects)
• Constructors
• Destructors
• Garbage Collection
• Static
• Command Line Arguments
• Inheritance
• Overloading and Overriding
• Abstract and Sealed
• Namespaces
• Structures

Copyright © 2005, 6 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 6
Recap of Object Oriented Concepts
• Classes
− templates used for defining new types.
− Contains attributes and behavior

• Instance of a class is called an Object

Copyright © 2005, 7 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

Classes lie at the heart of every object-oriented language. A class can be defined as
the encapsulation of data and the methods that work on that data.That’s true in any
object oriented or object based language.

ER/CORP/CRS/LA06/003 7
Recap of Object Oriented Concepts
• Encapsulation
− Mechanism that binds together code and the data it manipulates in a class
− Data members are made private and are prevented from being accessed
by outside classes thus achieves Data Hiding

• Inheritance
− Process by which one object can acquire the properties of another object.
− Supports hierarchical classification

• Polymorphism
-Ability of objects to respond in their own unique way to the same message

Copyright © 2005, 8 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 8
Structure of a C# program
using System;
namespace InsideCSharp
{
class FirstProgram
{
public static void Main()
{
Console.WriteLine(“Hello World”);
}
}
}

Copyright © 2005, 9 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

C# is an object oriented programming language. It supports features like Garbage


Collection, Versioning ,Language inter-operability and COM support. It provides
benefits like web compatibility ,minimum probability of errors and reduced cost of
developemnt.

Namespace is a means of semantically grouping elements such as classes to avoid


name collision.
System is a predefined namespace and InsideCSharp is a user defined namespace.
(Namespaces will be covered later in detail).
In the example , we have a single class named FirstProgram that contains a single
member – a method named Main.
Every C# application must define a Main method in one of its classes.
The public keyword (covered later in detail) is an access modifier that tells the C#
compiler that any code can call this method.
The static modifier (covered later in detail) tells the compiler that the Main method
is a global method and the class doesn’t need to instantiated for the method to be
called.
The given code shows the Main method as returning void and not receiving any
arguments. However, you can define Main method to return a value and take array
of arguments. (covered later in detail)

ER/CORP/CRS/LA06/003 9
Structure of a C# program

• The extension of a C# program is cs


• There is no restriction on the filename unless it follows the naming convention
of the OS
• Every statement in C# ends with ;
• Main is the starting point of execution of a C# program
• { } describes a block of code
• Main function must be written inside the class

Copyright © 2005, 10 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

Console is the name of a predefined class in C#.


Supports Console Input/Output.
Method WriteLine of the Console class displays information on the Console.

Console I/O is accomplished through standard streams Console.In, Console.Out and


Console.Error
Most of the C# applications will not be console based. Hence console based I/O is used in
simple teaching applications

To read a character, method Read is to be used.


To read a line of characters, method ReadLine is tobe used.

ER/CORP/CRS/LA06/003 10
Data Types

Value Types Reference Types

Value types include simple types like Reference types include class types,
char, int, and float, enum types, and interface types, delegate types, and
struct types array types

Variable holds the actual value Variable holds memory location

Allocated on stack Allocated on heap

Assignment of one value type to Assignment of one reference type to


another copies the value another copies the reference

Copyright © 2005, 11 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

All types are objects in the CTS and they all ultimately derive from System.Object.
The two main categories of types supported by the CTS : value types and reference
types.

ER/CORP/CRS/LA06/003 11
Data Types – Value Types
Data Types

Floating
Integer Character Boolean
Point

byte float Char bool

sbyte
double
short
decimal
ushort

int

uint

long

ulong

Copyright © 2005, 12 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

Unicode defines character set that is large enough to represent all human readable
characters

Bool data type represents true/false only. Does not represent any equivalent numeric
values
Ex: in C, a non zero value is true and 0 is false. Such a representation is not possible
in C#
The decimal data type uses 128 bits to represent values and used in monetary
calculations. the decimal type eliminates the rounding errors that occur in various
floating point calculations. the decimal type can accurately represent upto 28 decimal
places.

ER/CORP/CRS/LA06/003 12
Data Types – Value Types
Data Type Description Range
bool Represents true/false
byte 8 bit unsigned integer 0 to 255
sbyte 8 bit signed integer -128 to 127
short Short integer – 16 bits -32,768 to +32,767
ushort Unsigned short integer – 16 bits 0 to 65535
int Integer – 32 bits -2,147,483,648 to 2,147,483,647
uint Unsigned integer – 32 bits 0 to 4,294,967,295
long Long integer – 64 bits -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807

ulong Unsigned long integer – 64 bits 0 to 18,446,744,073,709,551,615

float Single precision floating point – 32 bits 1.5E-45 to 3.4E+38

double Double precision floating point – 64 bits 5E-324 to 1.7E+308

decimal Numeric type for financial calculations – 128 bits (supports 1E-28 to 7.9E+28
upto 28 decimal places)
char Character – 16 bit (uses Unicode)

Copyright © 2005, 13 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 13
Variables – Value Types
• Declaration syntax of a variable in C#:
<data type> <name of variable>
Ex:
int iNum;

• Initializing variables:
Ex:
int iNum = 10;

Variables in C# can be declared anywhere before referencing them.

The scope of the variable is from the declaration till the end of the block in which
it is declared.

Copyright © 2005, 14 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 14
What is the output of the following program?
using System;
class Test
{
public static void Main() ERROR
{ The variable iNum is still in
int iNum = 10; scope in the inner block
{
int iNum = 100;
Console.WriteLine(iNum);
}
Console.WriteLine(iNum);
}
}

Copyright © 2005, 15 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

To display data in a formatted way, use the following form of WriteLine:


Ex: WriteLine("format string", arg0, arg1, arg2 ...., argN);
The format string is of the form:
{argnum, width:fmt}
Ex: Console.WriteLine("LC is for {0} days",88);
The output is: LC is for 88 days.
In place of {0}, the value 88 is displayed.
Ex: specifying the field width:
Console.WriteLine("LC is {0,10} and SC is {1,5} days",88,49);
The output of the above statement is:
LC is 88 days and SC is 49 days
observe that spaces are added to fill in the unused fields.

ER/CORP/CRS/LA06/003 15
This slide has been intentionally left blank : Notes
Page Contd.

Copyright © 2005, 16 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

Ex: Format specifiers like \t can be used.


Console.WriteLine("{0}\t{1}\t",0,1);
The output is:
0 1
Ex: Console.WriteLine("value of 10/3: {0,#.##}",10.0/3);
The output is displayed upto 2 decimal places
value of 10/3: 3.33
Ex: Console.WriteLine("value is: {0,###,###.##}",123456.78);
The output is:
value is: 123,456.78
Ex: To display the currency - use C format specifier
Console.WriteLine("Amount is: {0:C}",1234);
The output is:
Amount is: $1234

ER/CORP/CRS/LA06/003 16
C# is a strongly typed language
• Automatic conversions (or widening conversions) from one type to another
takes place if:
− the source and the destination types are compatible
− the destination type is larger than the source type
Automatic conversions in C# does not happen that leads to data loss.

• Explicit conversions require type casting.

int iVal = 1234; double dVal = 34.23;

long lVal = iVal; float fVal = dVal;


The above statement does not
This implicit conversion compile as conversion from
does not lead to data loss double to float leads to data loss.

long lVal = 23456;


This is an example of
int iVal = (int) lVal; explicit conversion

Copyright © 2005, 17 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 17
Literals – Value Types
• Also called constants.
• Integer literals can be of type int, uint, long or ulong depending on their value.
Ex:
12l or 12L is of long type
12ul or 12UL is of ulong type
12u of 12U is of unsigned integer type, uint

• Floating point literals of type double


Ex:
12.3F or 12.3f is of type float
9.92M or 9.92m is of type decimal

• Boolean literals
Ex:
bool b = true;

Copyright © 2005, 18 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 18
Types
• Boxing
− Conversion of Value type to Reference Type
− Allocates box, copies value into it
• Unboxing
− Conversion of Reference Type back to Value Type
− Checks type of box, copies value out

int iVal = 123;


object oVal = iVal;
iVal;
int iValue = (int)oVal
(int)oVal;
;

iVal 123

oVal System.Int32
123
iValue 123

Copyright © 2005, 19 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

All types are derived from the object class, but the value types aren’t allocated on
the heap. Value type variables actually contain their values. so how then can
these types be stored in arrays and used in methods that expect reference
variables ?
Instead of writing wrapper code to convert from stack based memory to heap
memory, you just need to assign a value type to an object and C# takes care of
allocating the memory in the heap and generating a copy of that on the heap.
When you attribute the object to a stack based int, the value is converted to the
stack again. This process is what we call Boxing and Unboxing.
“Boxing” refers to the process of implicit conversion of a value type to a
reference type so that it can be manipulated like an object. Copies a value type
into a reference type (object).A reference-type copy is made of the value type.
Value type is converted implicitly to object, a reference type
“Unboxing” is inverse operation of boxing. Copies the value out of the box.
Copies from reference type to value type. Requires an explicit conversion. May
not succeed (like all explicit conversions)
Because of the allocation on the heap and copying the value type on to the heap it
results in performance overhead

ER/CORP/CRS/LA06/003 19
Control Structures – if statement
• Requires a boolean expression

int iNum = 10;


if ((iNum % 2) == 0)
{
Console.WriteLine("Even Number");
}
else
{
Console.WriteLine("Odd Number");
}

Copyright © 2005, 20 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 20
Control Structure – switch statement
• No two case constants in the same switch can have identical values.

• Fall through rule:


− Statement sequence from one case cannot continue to next case.
− Can be avoided by using the goto
− Default statement cannot fall through
− Empty cases can fall through.

Copyright © 2005, 21 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

Why C# does not allow fall through?


(1) C# compiler allows the case statements to be re arranged for optimization
(2) C# prevents a programmer from accidentally missing the break statement.

ER/CORP/CRS/LA06/003 21
Control Structure – switch statement
What is the output of the following code snippet?

int iNum=2;
switch(iNum)
{ compile error - control
cannot fall through from one
case 1: case to another
Console.WriteLine(iNum);
case 2:
Console.WriteLine(iNum);
break;
}

Copyright © 2005, 22 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 22
Control Structure – switch statement
char cChoice='i';
switch(cChoice)
{
case 'a':
case 'e':
case 'i': Vowels
case 'o':
case 'u':
Console.WriteLine("Vowels");
break;
default:
Console.WriteLine("Consonants");
break;
}

Copyright © 2005, 23 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 23
Control Structures - loops

while loop: do-while loop:


while (condition) do
{ {
statement/s ; statement/s;
} }while(condition)

for loop:
for (initialization; condition; iteration)
{
statement/s;
}

break;
continue;

Copyright © 2005, 24 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 24
Types – User defined types
Enumerations

Arrays

Class

Structure

Interface

Delegate

Copyright © 2005, 25 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

Interfaces and Delegates are covered on day2.

ER/CORP/CRS/LA06/003 25
Enumerations
• Enumeration is a set of named integer constants.
• General form of an enumeration:
enum name { enumeration list }
enum eColors { red, green, blue};

• The members of an enumeration are accessed through their type-name and


the dot operator.

The statement:
Console.WriteLine (eColors.green + “ has a value : “ +
(int) eColors.green);

Produces an output:
green has a value : 1

Copyright © 2005, 26 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

No two enum members can have the same name.


Examples of enums:
(1) Multiple enum members may share the same associated value. The example
enum Color { Red, Green, Blue, Max = Blue } shows an enum in which two enum
members — Blue and Max — have the same associated value.
(2) The example
enum Circular { A = B, B } results in a compile-time error because the declarations
of A and B are circular. A depends on B explicitly, and B depends on A implicitly.
(3) Each enum member has an associated constant value. The type of this value is
the underlying type for the containing enum. The constant value for each enum
member must be in the range of the underlying type for the enum. The example
enum Color: uint { Red = -1, Green = -2, Blue = -3 } results in a compile-time error
because the constant values -1, -2, and –3 are not in the range of the underlying
integral type uint.

ER/CORP/CRS/LA06/003 26
Enumerations
Consider:
enum eColors { red, green=10, blue} ;

What are the values of the members?


red Æ 0
green Æ 10
blue Æ 11

Copyright © 2005, 27 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 27
Arrays
Two ways of creating one dimensional array:
int [] aiNum;
aiNum = new int[10]; int [] aiNum = new int[10];

Two ways of initializing one dimensional array:

int [] aiNum;
int[] aiNum = {1,2,3};
aiNum = new int[] {1,2,3};

Two Dimensional array or rectangular array syntax:

int[,] aiNum = new int[10,20];

Copyright © 2005, 28 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

Arrays allow a group of elements of a specific type to be stored in a contiguous


block of memory
Since arrays are of reference types, new operator must be used to allocate memory
to arrays

ER/CORP/CRS/LA06/003 28
This slide has been intentionally left blank : Notes
Page Contd.

Copyright © 2005, 29 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

Example on 1D array:
using System;
///<summary>
///Class demonstrates array of integer values
///</summary>
class ArrayDemo
{
///<summary>
///Starting point of execution of the program
///</summary>
public static void Main()
{
int[] arrofNum = new int[10];
Console.WriteLine("Assign values to the array elements");
for( int index=0; index < arrofNum.Length; index++)
{
arrofNum[index] = index;
}
Console.WriteLine("Displaying the array elemens");
for( int index=0; index < arrofNum.Length; index++)
{
Console.WriteLine(arrofNum[index]);
} }}

ER/CORP/CRS/LA06/003 29
Jagged Arrays
• Are two dimensional arrays in which the number of elements in each row can
vary.

int[][] aiNum = new int[2][]; // array with 2 rows


aiNum[0] = new int[10]; // first row has 10 elements
aiNum[1] = new int[12]; // second row has 12 elements

Jagged Array

Copyright © 2005, 30 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 30
Types : Reference Type - Class
• Instantiated with new operator
• It consists of members like
− Constants, fields, methods, operators, constructors, destructors
− Properties, indexers, events
• Members can be
− Instance members.
− Static members.
class Employee
{
int iEmpId;
float fSalary;
void findSalary ()
{
// statements to calculate the salary
}
}
Copyright © 2005, 31 ER/CORP/CRS/LA30FC/003
Infosys Technologies Ltd Version no: 2.0

The syntax for defining classes in C# is simple

[attributes] [modifiers] class <classname> [:baseclassname]


{
[class – body]
}[;]

A member of a class can be defined as static member or an instance member. By


default, each member is defined as an instance member, which means that a copy of
that member is made for every instance of the class. When you declare a member a
static member, only one copy of the member exists. A static member is created
when the application containing the class is loaded, and it exists throughout the life
of an application. Therefore, you can access even before the class has been
instantiated.

ER/CORP/CRS/LA06/003 31
Object
• Steps to instantiate a class
Counter oCounterOne ;
oCounterOne = new Counter();

A reference oCounterOne
to the Counter class is
The new operator dynamically
created .oCounterOne does
allocates memory for an object of type
not define Counter
Counter and returns a reference to it.

Object
Note: The difference between a simple variable and the
reference type variable is that, simple variable holds the value
where a reference type variable points to a value.

Copyright © 2005, 32 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 32
Objects in memory
• Objects can be created in one step.
Ex: Counter oCounterOne = new Counter();

Reference
Po
Variable: int
oCounterOne st
o

Object of type Counter

Copyright © 2005, 33 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 33
Object Reference Assignment
Consider: Counter oCounterOne, oCounterTwo;

ocounterOne oCounterTwo

Statement: oCounterTwo = oCounterOne;


oCounterOne oCounterTwo

Object Reference

Copyright © 2005, 34 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 34
Access Modifiers
• Access modifiers specify who can use a type or a member
• Access modifiers control encapsulation
• Class members can be public, private, protected, internal, or
protected internal

If the access Then a member defined in type T and Program A


modifier is is accessible

public to everyone

private within T only

protected to T or types derived from T

internal to types within A

to T or types derived from T


protected internal
or to types within A

Copyright © 2005, 35 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

The access modifiers with their description are as follows -


public – Signifies that the member is accessible from outside the class’s definition
and hierarchy of derived classes.
protected – The member isn’t visible outside the class and can be accessed by
derived classes only.
private-The member can’t be accessed outside the scope of the defining class.
Therefore, not even derived classes have access to these members.
Internal- The member is visible only within the current compilation unit.
Default access modifier for a member is private.

ER/CORP/CRS/LA06/003 35
Class - Fields
• A field
− is a member variable of a class
− holds data for a class .By default each object of a class has its own copy of every
field
• Static fields are shared by multiple objects.

public float fSalary;

Copyright © 2005, 36 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

A field is a member variable used to hold a value. You can apply several modifiers
to a field ,depending on how you want the field used .The modifiers include static,
readonly and const. We’ll discuss what these modifiers signify and how to use them
shortly.

ER/CORP/CRS/LA06/003 36
Class – Read only Fields
• Read only fields are constants
• A read only field cannot be modified once initialized.
• Are initialized in its declaration or in a constructor.

public class MyClass {


public static readonly double dNum = Math.Sin(Math.PI);
public readonly string sStrOne;
public MyClass(string sStr) { sStrOne = sStr; } }

Copyright © 2005, 37 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

There will certainly be times when you have fields that you don’t want altered
during execution of the application. To address these situations, C# allows for
the definition of two closely related member types : constants and read-only
fields.
Constants ,represented by the const keyword – are fields that remain constant
for the life of the application and their value is set at compile-time.
When you define a field with the read-only keyword, you have the ability to
set that field’s value in one place : constructor.

ER/CORP/CRS/LA06/003 37
Class – Methods
• All the executable code of a class is in its methods
• Constructors, destructors and operators are special types of methods
• Methods can have argument lists, statements, can return a value
• By default, data is passed by value where a copy of the data is created and
passed to the method

Copyright © 2005, 38 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

Methods give classes their behavioral characteristics, and we name methods after
the actions we want the classes to carry out on our behalf.
A method is the actual code that acts on the object’s data (or field values).

ER/CORP/CRS/LA06/003 38
A complete class
/// <summary>
/// This is a counter class to count
/// </summary>
class Counter Class comment
{ block
//Counter variable
private int iCount;
/// <summary>
/// This method is used to increment the value of the
count.
/// </summary>
public void increment()
{ Method
iCount++; comment block
}
}

Copyright © 2005, 39 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 39
Methods - ref parameters
ref modifier:
• The ref modifier causes arguments to be passed by reference
• The ref modifier has to be used in the method definition and the code that
calls it
void RefFunction(ref int iP)
{
iP++;
}

Call statement:

int iNum = 10;


RefFunction(ref iNum);
// iNum is now 11

Copyright © 2005, 40 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ref keyword tells the C# complier that the arguments being passed point to the same
memory as the variables in the calling code.That way,if the called method modifies
the values and then returns, the calling code’s variables are modified.

Reference type variables are passed by reference to a method. but the reference of
the object is passed by value. if you want the reference to be passed by reference,
then use ref keyword along with the object.

ER/CORP/CRS/LA06/003 40
This slide has been intentionally left blank : Notes
Page Contd.

Copyright © 2005, 41 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

Ex: using ref parameter


using System;

class RefSwap {
int a, b;
public RefSwap(int i, int j) {
a = i;
b = j;
}
public void show() {
Console.WriteLine(" a: {0}, b: {1}" ,a, b);
}
public void swap( ref RefSwap ob1, ref RefSwap ob2) {
RefSwap t;
t = ob1;
ob1 = ob2;
ob2 = t;
}
}

ER/CORP/CRS/LA06/003 41
This slide has been intentionally left blank : Notes
Page Contd.

Copyright © 2005, 42 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

class RefSwapDemo {
public static void Main() {
RefSwap x = new RefSwap(1,2);
RefSwap y = new RefSwap(3,4);
Console.Write("x before call");
x.show();
Console.Write("y before call");
y.show();
Console.WriteLine();
x.swap( ref x, ref y);
Console.Write("X after call");
x.show();
Console.Write("y after call");
y.show();
}
}

ER/CORP/CRS/LA06/003 42
Methods - out parameters
out modifier:
• the out parameter is used in cases where you need to return a value from a
method, but not pass a value to the method.
• use out parameter to return more than one value from the method.
• out parameter will not have any initial values but must be assigned a value
before the method terminates.

Out Parameter

Copyright © 2005, 43 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

C# provides an alternate means of passing an argument whose changed value must


be seen by the calling code : the out keyword. The significant difference between
the ref keyword and the out keyword is that the out keyword doesn’t require the
calling code to initialize the passes arguments first.

ER/CORP/CRS/LA06/003 43
Methods – passing variable number of arguments
• Methods can have a variable number of arguments, called a parameter array
• params keyword declares parameter array
• This must be last argument of the method and there can be only one such
argument.

int Sum(params int[] aiArr) {


int iSum = 0;
foreach (int iNum in aiArr)
iSum += iNum;
return iSum;
}

int iTotal = Sum(13,87,34);


Parameter

Copyright © 2005, 44 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

The params parameter can be a variable number of parameters. params parameter


allows us to gain the simplicity of treating all types as objects but pay a performance
penalty when you need to treat those same parameters as specific types rather than
generic objects.

ER/CORP/CRS/LA06/003 44
this keyword
• When a local variable of a method has the same name as that of the instance
variable, the local variable hides the instance variable.
• In such cases, "this" can be used to refer to the instance variables.
class Demo
{
int i; // instance variable
public void fun (int i)
{
i = 10; // the local variable is referred
this.i = i; // to refer to the instance variable, this
is used
}
}

Copyright © 2005, 45 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 45
static
• use static to define a member that is independent of any objects
• static members can not be accessed using an object of a class. instead, they
are accessed using the syntax:
classname.staticmembername
• when objects of a class containing static members are created, a copy of the
static members are not made
• all the instances of the class share the same static variable

+Restrictions on static methods:


(a) this cannot be used in static methods
(b) static methods can call only static methods - because instance
methods act on specific instances of the class but static methods do not.
(c) static methods can access static data directly.

Copyright © 2005, 46 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

A static member is a member that exists in a class as a whole ,rather than in a


specific instance of the class. The key benefit of static method is that they reside
apart from a particular instance of a class without polluting the application’s global
space and without going against the object-oriented grain by not being associated
with a class.
If no initial values for a static variable are specified, then numeric values are
initialized to zero and null for reference types.

ER/CORP/CRS/LA06/003 46
What is the output of the following code snippet?
using System;
Compilation error: a non
class Test
static method cannot be
{ called from a static method
public static void Main()
{
anotherMethod();
}
void anotherMethod()
{
Console.WriteLine(“Another Method”);
}
}

Copyright © 2005, 47 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

The correct form:


using System;
class Test
{
public static void Main()
{
Test t = new Test();
t.anotherMethod();
}
void anotherMethod()
{
Console.WriteLine(“Another Method”);
}
}

ER/CORP/CRS/LA06/003 47
Method Overloading
• Two or more methods within the same class can have same name, but the
parameters must vary.
• In general, the type or the number of parameters must differ.
• The signature (name of the method and its parameter list) does not include a
params parameter if one is present. params does not participate in
overloading

Method Overload

Copyright © 2005, 48 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

Method overloading enables the C# programmer to use the same method name
multiple times with only the passes arguments changed.
In C#, the signature includes the name of the method plus its parameter list. Note, it
does not include the return type.

ER/CORP/CRS/LA06/003 48
Constructor
• Is special method that is called whenever an instance of the class is created.
• It guarantees that the object will go through proper initialization before being
used.
• It is without any return value.
• It has same name as its class.
• Access specifier must be public as constructors are called from outside the
class.
• It can be overloaded.

Constructor

Copyright © 2005, 49 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

Constructors are special methods that are called when-ever an instance of the class is created. A key
benefit of using a constructor is that it guarantees that the object will go through proper initialization
before being used. When a user instantiates an object, that object’s constructor is called and must
return before the user can perform any other work with that object. This guarantee helps ensure the
integrity of the object and helps make applications written with object-oriented languages much more
reliable.

If a class doesn’t define any constructors, an implicit parameter less constructor is created
If a parameterized constructor is defined, then the default constructor is no longer used.

If no constructor is implemented then the default constructor is supplied.


The default constructor initializes the data members with default values.
If the constructors are implemented then no default constructor will be supplied

By overloading the constructor, you are giving flexibility to users the way in which objects can be
created.
Invoking an overloaded constructor using this: to invoke an overloaded constructor, you can use the
this keyword.

ER/CORP/CRS/LA06/003 49
This slide has been intentionally left blank : Notes
Page Contd.

Copyright © 2005, 50 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

using System;
class Demo
{
int x;
int y;
Demo(int i, int j)
{
Console.WriteLine("invoking two arg constructor");
x = i;
y = j;
}
Demo(int x) : this(x,x)
{
Console.WriteLine("invoking the one arg constructor");
}
Demo() : this(0,0)
{
Console.WriteLine("invoking the default constructor");
}
Demo( Demo d) : this(d.x, d.y) {
{
Console.WriteLine("invoking the one arg constructor - object");
}}

ER/CORP/CRS/LA06/003 50
This slide has been intentionally left blank : Notes
Page Contd.

Copyright © 2005, 51 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

class Test
{
public static void Main()
{
Demo d1 = new Demo();
Demo d2 = new Demo(10);
Demo d3 = new Demo(10,20);
Demo d4 = new Demo(d2);
}
}

ER/CORP/CRS/LA06/003 51
Static Constructors
• used to initialize the static variables
• access modifiers like public are not allowed on static constructors
• are called only once during the lifetime of the program

Static Constructor

Copyright © 2005, 52 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

A static constructor is handled in a special way : you can have only one static
constructor ,it can’t take parameters, and it course can’t access instance members –
including this pointer. A static constructor is executed before the first instance of a
class is created. Access modifiers such a public and private aren’t allowed on static
constructors.

ER/CORP/CRS/LA06/003 52
Destructors
• A destructor is a method that is called when an instance goes out of scope
• Used to clean up any resources
• Only classes can have destructors

~Employee()
{
// destruction code
}

Copyright © 2005, 53 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

C# destructors are not guaranteed to be called at a specific time


Destructor is called prior to garbage collection and not when the object goes out of
scope.
Ex: showing the destructors
using System;
class Demo
{
public static void Main()
{
DestructorDemo d = new DestructorDemo(0);
for (int i=0; i<100000; i++) {
// create many objects that garbage collection must occur
d.generateObject(i);
}
}
}

ER/CORP/CRS/LA06/003 53
This slide has been intentionally left blank : Notes
Page Contd.

Copyright © 2005, 54 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

class DestructorDemo {
public int i;
public DestructorDemo(int x)
{
i = x;
}
~DestructorDemo()
{
Console.WriteLine("Destructor called");
}
// object is created here which goes out of scope immediately
public void generateObject(int s)
{
DestructorDemo d = new DestructorDemo(s);
}
}

ER/CORP/CRS/LA06/003 54
Garbage Collection
• Automatic Memory Management Scheme

• Garbage Collector always run in background of an application.

Copyright © 2005, 55 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

An automatic garbage collector cleans up the heap memory on your behalf when it’s
no longer needed. GC traces object references and identifies objects that can no
longer be reached by running code. The GC doesn’t take up processor resources by
running constantly, but it kicks periodically.
A consequence of this last point is that heap memory garbage collection – and ,by
extension ,object destruction – is nondeterministic. That is , under normal
circumstances , you can’t be absolutely sure when the GC will run and therefore
when your object will be finally destroyed .

You can force a garbage collection operation at any time with GC.Collect method.

ER/CORP/CRS/LA06/003 55
Finalize
• Finalize method is defined in Object class.

• A finalizer executes when the object is destroyed.

• In C# the declaration of the destructor is a short cut for the Finalize() method.

Copyright © 2005, 56 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

The Finalize method is called automatically after an object becomes inaccessible.


The C# language doesn’t strictly support destructors. On the other hand, it does
support overriding the Object.Finalize method. The only twist in the tale is that to
override Finalize , you must write a method that’s syntactically identical to a
destructor.

In C# the declaration of the destructor is a short cut for the Finalize() method.
A finalizer executes when the object is destroyed. The finalizer is a protected
method named Finalize
Ex : protected void Finalize(){
}

ER/CORP/CRS/LA06/003 56
Dispose
• Free resources that need to be reclaimed as quickly as possible.

• Explicitly called.

public void Dispose()


{
Console.WriteLine(“Dispose()”);
}

Copyright © 2005, 57 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

To achieve necessary explicit control and precise determinism in the destructor-like


cleanup of unmanaged resources, you’re encouraged to implement an arbitrary
Dispose method . The consumer of the object should call this method when the
object is no longer required. This call can be made even if other references to the
object are alive. Unlike, the finalizer , the Dispose method is arbitrary – in terms of
its name, signature, access modifiers and attributes. You’re encouraged to use a
public nonstatic method named Dispose ,with a void return and no parameters. This
is only convention.

ER/CORP/CRS/LA06/003 57
Operators - overview
• C# provides a fixed set of operators, whose meaning is defined for the
predefined types
• Some operators can be overloaded (e.g. +)
• Associativity
− Assignment and ternary conditional operators are right-associative
• Operations performed right to left
• x = y = z evaluates as x = (y = z)
− All other binary operators are left-associative
− Operations performed left to right
− x + y + z evaluates as (x + y) + z
− Use parentheses to control order

Copyright © 2005, 58 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

C# operator precedence is as follows - Primary, Unary, Multiplicative ,Additive


,Shift, Relational ,Equality ,Logical AND , Logical XOR , Logical OR
,Conditional AND ,Conditional OR ,Conditional and Assignment.

ER/CORP/CRS/LA06/003 58
Operator Overloading
• Operator Overloading helps in creating user-defined operations
• The method used to overload the operator must be a static method

class Car {
string vid;
public static bool operator ==(Car x, Car y) {
return x.vid == y.vid;
}
}

Copyright © 2005, 59 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

Operator overloading allows existing C# operators to be redefined so that one or


both of the operator’s operands are of a user defined or struct type.

Restrictions on operator overloading


(1) Precedence of the operators cannot be changed
(2) Cannot alter the number of operands of the operator
(3) You cannot overload any assignment operators such as += etc… - this cannot be
overloaded explicitly. But if += is used, automatically, the operator+ is called
(4) You cannot overload the [] operator but indexers can be used for the same
purpose.

ER/CORP/CRS/LA06/003 59
Operator Overloading
• Overloadable unary operators
+ - ! ~
true false ++ --

• Overloadable binary operators

+ - * / ! ~

% & | ^ == !=

<< >> < > <= >=

Operator Overload

Copyright © 2005, 60 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

Overloading is not allowed for member access, method invocation, assignment


operators, nor these operators: sizeof, new, &&, ||, and ?:.
The && and || operators are automatically evaluated from & and |
Overloading a binary operator (e.g. *) implicitly overloads the corresponding
assignment operator (e.g. *=)

ER/CORP/CRS/LA06/003 60
Inheritance
• Using inheritance, you can create a general class that defines a common set of
attributes and behaviors for a set of related items.
• A derived class is a specialized version of the base class and inherits all the
fields, properties, operators and indexers defined by base class
• Protected members are private to the class but can be inherited and accessed
by the derived class

The constructor of the base class can be called from the derived class using the
keyword base.

Inheritance

Copyright © 2005, 61 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

Inheritance is used when a class is built upon another class, in terms of data or
behaviour.
To inherit one class from another, use the following syntax
class <derivedclass>: <baseclass>

Private members of the base class will not be inherited to the derived class.

ER/CORP/CRS/LA06/003 61
Hidden Names and Inheritance
using System; class InheritanceTest
class Parent {
{
public static void Main()
protected int p;
public Parent() {
{ Child c = new Child();
p = 10; c.displayParent();
} }
}
}
class Child : Parent
{ What does the statement
int p; c.displayParent() display?
public Child()
{ The child class member p hides the member p
p = 100; of the parent class.
}
public void displayParent() To access the member p of the Parent class,
{ use the syntax: base.member.
Console.WriteLine(p); Refer to notes page for the above modified
} program
}

Copyright © 2005, 62 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

using System;
///<summary>
///Class representing the Parent
///</summary>
class Parent
{
protected int p;
///<summary>
///Constructor of class Parent
///</summary>
public Parent()
{
p = 10;
}
}
///<summary>
///Class inheriting the class Parent
///</summary>
class Child : Parent
{
int p;
///<summary>
///Constructor of Child class
///</summary>
public Child()
{
p = 100;
}

ER/CORP/CRS/LA06/003 62
This slide has been intentionally left blank : Notes
Page Contd.

Copyright © 2005, 63 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

///<summary>
///Method to display the Parent class’s member p
///</summary>
public void displayParent()
{
Console.WriteLine(base.p);
}
}

///<summary>
///Class testing the Parent and Child classes
///</summary>
class InheritanceTest
{
///<summary>
///Starting point of execution of the program
///</summary>
public static void Main()
{
Child c = new Child();
c.displayParent();
}
}

ER/CORP/CRS/LA06/003 63
Base class reference can refer to a derived class
object
• A derived class object can be assigned to a base class reference
• But the parent class reference cannot access the members of the derived class

Base Class
Reference

Copyright © 2005, 64 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 64
Method Overriding and Virtual Methods
• Method of a derived class can give another implementation to a method of the
base class
• Method of the base class must be marked “virtual”
• Method of the derived class must be marked “override”
class Employee //base class class Manager : Employee
{ {
protected double basic; protected double allow;
protected double gross; public override void
public virtual void CalcSal()
CalcSal() {
{ gross = basic +
gross = basic + 0.5*basic; 0.5*basic + allow;

} }

} }

Copyright © 2005, 65 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

In inheritance, a derived class can give another implementation to a method of the


base class. This is method overriding.
to achieve overriding, the method of the base class must be marked as “virtual” and
the method of the derived class must be marked as “override”
Ex:
class Employee
{
protected double basic;
protected double gross;
public virtual void CalcSal()
{
gross = basic + 0.5*basic;
}
}

class Manager : Employee


{
protected double allowances;
public override void CalculateSalary()
{
gross = basic + 0.5*basic + allowances;
}
}

ER/CORP/CRS/LA06/003 65
This slide has been intentionally left blank : Notes
Page Contd.

Copyright © 2005, 66 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

Note: If the method of base class is not marked “virtual”, even then it can be
overridden in derived class by marking it new.
Ex:
class Employee
{
protected double basic;
protected double gross;
public void CalcSal()
{
gross = basic + 0.5*basic;
}
}
class Manager : Employee
{
protected double allowances;
public new void CalculateSalary()
{
gross = basic + 0.5*basic + allowances;
}
}

ER/CORP/CRS/LA06/003 66
Sealed modifier : methods
• Applied to methods:
− Cannot be overridden
ERROR

class class1
{
class class2 : class1
public override sealed int F1()
{ {
……. public override int F1()
} {
} ………
}
}

Copyright © 2005, 67 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

Sealed methods:
In C# methods can not be declared as sealed directly
But a overriding method can be declared as sealed
By doing so further overriding of the method can be avoided

ER/CORP/CRS/LA06/003 67
Sealed modifier : Class
• Applied to class
− Cannot be derived
ERROR

sealed class class1


{
} class class2 : class1
{

Copyright © 2005, 68 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

Sealed class:
A sealed class is one that cannot be used as a base class
Sealed classes can’t be abstract
A class is sealed to prevent unintended derivation

ER/CORP/CRS/LA06/003 68
Abstract modifier
• Applied to methods:
− Methods cannot have implementation in base class
− Must be implemented in derived class and marked “override”
− The class containing at least one abstract method must be declared
abstract
class Manager : Employee
//base class {
abstract class Employee protected double allow;
{ public override void
protected double basic; CalcSal()

protected double gross; {

public abstract void gross = basic +


CalcSal(); 0.5*basic + allow;

} }
}

Copyright © 2005, 69 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

The abstract keyword can be used for method and class

An abstract method signifies it has no body (implementation), only declaration of


the method followed by a semicolon

public abstract double calculateArea();


If a class has one or more abstract methods declared inside it, the class must be
declared abstract

An abstract class cannot be instantiated ie objects cannot be created from an abstract


class

Reference of an abstract class can point to objects of its sub-classes thereby


achieving run-time polymorphism

ER/CORP/CRS/LA06/003 69
Abstract modifier - Demos

Abstract (class1.cs) Abstract


(Class2.cs)

Copyright © 2005, 70 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

An abstract class is an incomplete class that cannot be instantiated


Intended to be used as a base class
May contain abstract and non-abstract function members
Similar to an interface
Abstract classes cannot be sealed

ER/CORP/CRS/LA06/003 70
Namespaces
• Namespaces provide a way to uniquely identify a type.
• Provides logical organization of types.
• Namespaces can span assemblies.
• Can be nested.
• The fully qualified name of a type includes all namespaces.
namespace N1 { // is referred to as N1
class C1 { // is referred to as N1.C1 Fully Qualified
class C2 { // is referred to as N1.C1.C2 name
}
}
namespace N2 { // is referred to as N1.N2
class C2 { // is referred to as N1.N2.C2 Namespace
}
}
}

Copyright © 2005, 71 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

Namespaces are compilation units that let you organize and reuse code.
There is no relationship between namespaces and file structure (unlike Java)

The using statement is used use types without typing the fully qualified name
fully qualified name can also be used
Ex:
using N1;
C1 a; // The N1. is implicit
N1.C1 b; // Fully qualified name
C2 c; // Error! C2 is undefined
N1.N2.C2 d; // One of the C2 classes
C1.C2 e; // The other one
The using statement can also be used to create aliases
using C = N1.N2.C1;
using N = N1.N2;
C a; // Refers to N1.N2.C1
N.C1 b; // Refers to N1.N2.C1

ER/CORP/CRS/LA06/003 71
Predefined Types - Object
• Root of object hierarchy
• Storage (book keeping) overhead
− 0 bytes for value types
− 8 bytes for reference types

Copyright © 2005, 72 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

All data types inherit from the System.Object class in the .Net framework, which is
aliased as object.

ER/CORP/CRS/LA06/003 72
Predefined Types - String
• A sequence of characters
• Strings are immutable (once created the value does not change)
• String is Reference type and string class in C# is an alias of System.String
class in the dot net framework
• The following special syntax for string literals is allowed as they are built in
data types.
− String s = “I am a string”;

C# Type System Type

String System.String

Copyright © 2005, 73 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

System.String class (or its alias , string) represents an immutable string of


characters. Methods like Replace(), Insert() etc. that appear to modify a string
actually return a new string containing the modification.

ER/CORP/CRS/LA06/003 73
Predefined Types - StringBuilder
• Every time some modifications are done to the string a new String object
needs to be created
• StringBuilder class can be used to modify string without creating a new string
− Ex : StringBuilder str = new StringBuilder (“hi”);
• Properties:
− Length
• Methods
− Append() String Builder
− Insert()
− Remove()
− Replace()
StringBuilder str = new StringBuilder (“hi”);
str.Append(“how are you?”)
str.Insert(6,”How do you do?”);

Copyright © 2005, 74 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

StringBuilder class is provided in System.Text namespace.

ER/CORP/CRS/LA06/003 74
Command Line Arguments
• Arguments can be passed to Main function at the command prompt from
where the program is invoked.
• Main function can return an integer .
• Four forms of Main:
− public static void Main()
− public static int Main()
− public static void Main(string[] args)
− public static int Main(string[] args)

Command Line
Arguments

Copyright © 2005, 75 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

The arguments specified at the command prompt will be put in an array of String
type.
In case we need to pass a numeric value at the command prompt, then we have to
perform conversion from String to numeric type.
Convert class can be used to convert from one base type to any other base type. In
case of incompatible conversion, an exception is thrown.
Following are few overloaded methods for conversion:
Convert.ToDouble -> Converts a specified value to a double-precision floating point
number.
Convert.ToDecimal -> Converts a specified value to a Decimal number.
Convert.ToInt64 -> Converts a specified value to a 64-bit unsigned integer.

ER/CORP/CRS/LA06/003 75
Structure
•Is a generalization of a user-defined data type (UDT)-Value type.
•Is created when you want a single variable to hold multiple types of related
data.
•Is declared by using the keyword struct.
•Can also include methods as its members.
•member access levels possible are only public, internal, private

Structure

Copyright © 2005, 76 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

Like a class, a struct can contain other types and is sometimes referred to as a
lightweight version of a class because internally it is a value type.
The members of a structure are same as members in a class

Defining a struct takes an almost identical form to that of defining a class


[attributes] [modifiers] struct <structname> [:interfaces]
{
[struct–body]
}[;]

Multiple interface inheritance is possible .Structures can implement one or more


interfaces (Interfaces are discussed on Day 2)
Members of the structure cannot be specified as abstract, virtual or protected

ER/CORP/CRS/LA06/003 76
This slide has been intentionally left blank : Notes
Page Contd.

Copyright © 2005, 77 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

using System;
struct Point
{
public int x;
public int y;
public Point(int x,int y)
{
this.x=x;
this.y=y;
}

public Point Add(Point pt)


{
Point newPt;
newPt.x = x + pt.x;
newPt.y = y+pt.y;
return newPt;
}
}

ER/CORP/CRS/LA06/003 77
This slide has been intentionally left blank : Notes
Page Contd.

Copyright © 2005, 78 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

class StructExample
{
static void Main(string [] args)
{
Point pt1 = new Point(1,1);
Point pt2 = new Point(2,2);
Point pt3;
pt3= pt1.Add(pt2);
Console.WriteLine("p3 : {0} : {1}",pt3.x,pt3.y);
}
}

ER/CORP/CRS/LA06/003 78
Structure and Class - Similarities
• Both can have members, including constructors, properties, constants, and
events.

•Both can implement interfaces.


•Both can have static constructors, with or without parameters.

Copyright © 2005, 79 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 79
Structure and Class - Differences

Class Structure
A class is inheritable from other existing A structure is not inheritable.
classes.
A class can have instance constructors A structure can have instance
with or without parameters. constructors only if they take
parameters.
A class is a reference type. A structure is a value type.

Copyright © 2005, 80 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 80
Summary
• Recap of OO
• Basic Data Types and Control Structures
• Structure
• Classes and Objects
• Garbage Collection
• Static
• Command Line Arguments
• Inheritance
• Overloading and Overriding
• Abstract and Sealed
• Namespaces
• Structures

Copyright © 2005, 81 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 81
Thank You!

Copyright © 2005, 82 ER/CORP/CRS/LA30FC/003


Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 82