Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 72

C Sharp Programming – Day 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
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
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
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
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
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
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
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
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
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 another Assignment of one reference type to


copies the value another copies the reference

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


Infosys Technologies Ltd Version no: 2.0
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
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
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
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
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
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
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;
int iValue = (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
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
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
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
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
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;

Copyright © 2005,
continue; 24 ER/CORP/CRS/LA30FC/003
Infosys Technologies Ltd Version no: 2.0
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
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
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
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
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
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
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
Objects in memory
• Objects can be created in one step.
Ex: Counter oCounterOne = new Counter();

Reference
Po
Variable: int
oCounterOne s to

Object of type Counter

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


Infosys Technologies Ltd Version no: 2.0
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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

• 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
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
Hidden Names and Inheritance
using System; class InheritanceTest
class Parent
{
{
protected int p; public static void Main()
public Parent() {
{ Child c = new Child();
p = 10; c.displayParent();
}
} }
class Child : Parent }
{ What does the statement
int p; c.displayParent() display?
public Child()
{
p = 100; The child class member p hides the member p 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
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
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
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 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
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
Abstract modifier - Demos

Abstract (class1.cs) Abstract


(Class2.cs)

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


Infosys Technologies Ltd Version no: 2.0
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 Namespace
class C2 { // is referred to as
N1.N2.C2    
}
}

}
Copyright © 2005, 71 ER/CORP/CRS/LA30FC/003
Infosys Technologies Ltd Version no: 2.0
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
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
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
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
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
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
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
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
Thank You!

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


Infosys Technologies Ltd Version no: 2.0

You might also like