Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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
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
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
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/
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
ER/CORP/CRS/LA06/003 6
Recap of Object Oriented Concepts
• Classes
− templates used for defining new types.
− Contains attributes and behavior
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
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”);
}
}
}
ER/CORP/CRS/LA06/003 9
Structure of a C# program
ER/CORP/CRS/LA06/003 10
Data 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
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
sbyte
double
short
decimal
ushort
int
uint
long
ulong
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
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)
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;
The scope of the variable is from the declaration till the end of the block in which
it is declared.
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);
}
}
ER/CORP/CRS/LA06/003 15
This slide has been intentionally left blank : Notes
Page Contd.
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.
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
• Boolean literals
Ex:
bool b = true;
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
iVal 123
oVal System.Int32
123
iValue 123
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
ER/CORP/CRS/LA06/003 20
Control Structure – switch statement
• No two case constants in the same switch can have identical values.
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;
}
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;
}
ER/CORP/CRS/LA06/003 23
Control Structures - loops
for loop:
for (initialization; condition; iteration)
{
statement/s;
}
break;
continue;
ER/CORP/CRS/LA06/003 24
Types – User defined types
Enumerations
Arrays
Class
Structure
Interface
Delegate
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 statement:
Console.WriteLine (eColors.green + “ has a value : “ +
(int) eColors.green);
Produces an output:
green has a value : 1
ER/CORP/CRS/LA06/003 26
Enumerations
Consider:
enum eColors { red, green=10, blue} ;
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];
int [] aiNum;
int[] aiNum = {1,2,3};
aiNum = new int[] {1,2,3};
ER/CORP/CRS/LA06/003 28
This slide has been intentionally left blank : Notes
Page Contd.
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.
Jagged Array
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
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.
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
ER/CORP/CRS/LA06/003 33
Object Reference Assignment
Consider: Counter oCounterOne, oCounterTwo;
ocounterOne oCounterTwo
Object Reference
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
public to everyone
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.
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.
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
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
}
}
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:
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.
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.
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
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.
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
}
}
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
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”);
}
}
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
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
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.
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.
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.
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
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
}
ER/CORP/CRS/LA06/003 53
This slide has been intentionally left blank : Notes
Page Contd.
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
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.
• In C# the declaration of the destructor is a short cut for the Finalize() method.
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.
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
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;
}
}
ER/CORP/CRS/LA06/003 59
Operator Overloading
• Overloadable unary operators
+ - ! ~
true false ++ --
+ - * / ! ~
% & | ^ == !=
Operator Overload
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
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
}
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.
///<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
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;
} }
} }
ER/CORP/CRS/LA06/003 65
This slide has been intentionally left blank : Notes
Page Contd.
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()
} {
} ………
}
}
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:
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()
} }
}
ER/CORP/CRS/LA06/003 69
Abstract modifier - Demos
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
}
}
}
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
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”;
String System.String
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?”);
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
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
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
ER/CORP/CRS/LA06/003 76
This slide has been intentionally left blank : Notes
Page Contd.
using System;
struct Point
{
public int x;
public int y;
public Point(int x,int y)
{
this.x=x;
this.y=y;
}
ER/CORP/CRS/LA06/003 77
This slide has been intentionally left blank : Notes
Page Contd.
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.
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.
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
ER/CORP/CRS/LA06/003 81
Thank You!
ER/CORP/CRS/LA06/003 82