c# language overview part ii

101
C# Language C# Language Overview Overview (Part II) (Part II) Creating and Using Objects, Creating and Using Objects, Exceptions, Strings, Generics, Exceptions, Strings, Generics, Collections, Attributes Collections, Attributes Doncho Minkov Doncho Minkov Telerik School Academy Telerik School Academy schoolacademy.telerik .com Technical Trainer Technical Trainer http://www.minkov.it

Upload: doncho-minkov

Post on 06-May-2015

2.338 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: C# Language Overview Part II

C# Language C# Language OverviewOverview

(Part II)(Part II)Creating and Using Objects, Exceptions, Creating and Using Objects, Exceptions,

Strings, Generics, Collections, Strings, Generics, Collections, AttributesAttributes

Doncho MinkovDoncho Minkov

Telerik School AcademyTelerik School Academyschoolacademy.telerik.com

Technical TrainerTechnical Trainerhttp://www.minkov.it

Page 2: C# Language Overview Part II

Table of ContentsTable of Contents

1.1. Creating and Using ObjectsCreating and Using Objects

2.2. Exceptions HandlingExceptions Handling

3.3. Strings and Text ProcessingStrings and Text Processing

4.4. GenericsGenerics

5.5. Collection ClassesCollection Classes

6.6. AttributesAttributes

2

Page 3: C# Language Overview Part II

Using Classes and Using Classes and ObjectsObjectsUsing the Standard .NET Framework Using the Standard .NET Framework

ClassesClasses

Page 4: C# Language Overview Part II

What is Class?What is Class?

The formal definition of The formal definition of classclass::

Definition by GoogleDefinition by Google

4

ClassesClasses act as templates from act as templates from which an instance of an object which an instance of an object is created at run time. Classes is created at run time. Classes define the properties of the define the properties of the object and the methods used object and the methods used to control the object's to control the object's behavior.behavior.

Page 5: C# Language Overview Part II

ClassesClasses Classes provide the structure for Classes provide the structure for

objectsobjects Define their prototype, act as templateDefine their prototype, act as template

Classes define:Classes define: Set of Set of attributesattributes

Represented by fields and propertiesRepresented by fields and properties

Hold their Hold their statestate

Set of actions (Set of actions (behaviorbehavior)) Represented by methodsRepresented by methods

A class defines the methods and types A class defines the methods and types of data associated with an objectof data associated with an object

5

Page 6: C# Language Overview Part II

Classes – ExampleClasses – Example

6

AccountAccount

+Owner: Person+Owner: Person+Ammount: double+Ammount: double

+Suspend()+Suspend()+Deposit(sum:double+Deposit(sum:double))+Withdraw(sum:doubl+Withdraw(sum:double)e)

Class Class NameName

AttributAttributeses

(Properti(Properties and es and Fields)Fields)

OperatioOperationsns

(Method(Methods)s)

Page 7: C# Language Overview Part II

ObjectsObjects An An objectobject is a concrete is a concrete instanceinstance of a of a

particular class particular class Creating an object from a class is Creating an object from a class is

called called instantiationinstantiation Objects have stateObjects have state

Set of values associated to their Set of values associated to their attributesattributes

Example:Example: Class: Class: AccountAccount Objects: Ivan's account, Peter's accountObjects: Ivan's account, Peter's account

7

Page 8: C# Language Overview Part II

Objects – ExampleObjects – Example

8

AccountAccount

+Owner: Person+Owner: Person+Ammount: double+Ammount: double

+Suspend()+Suspend()+Deposit(sum:double+Deposit(sum:double))+Withdraw(sum:doubl+Withdraw(sum:double)e)

ClassClass ivanAccountivanAccount

+Owner="Ivan +Owner="Ivan Kolev"Kolev"+Ammount=5000.0+Ammount=5000.0

peterAccountpeterAccount

+Owner="Peter +Owner="Peter Kirov"Kirov"+Ammount=1825.33+Ammount=1825.33

kirilAccountkirilAccount

+Owner="Kiril +Owner="Kiril Kirov"Kirov"+Ammount=25.0+Ammount=25.0

ObjeObjectct

ObjeObjectct

ObjeObjectct

Page 9: C# Language Overview Part II

Classes in C#Classes in C# Basic units that compose programsBasic units that compose programs Implementation is Implementation is encapsulatedencapsulated

(hidden) (hidden) Classes in C# can contain:Classes in C# can contain:

Fields (member variables)Fields (member variables) PropertiesProperties MethodsMethods ConstructorsConstructors Inner typesInner types Etc. (events, indexers, operators, …)Etc. (events, indexers, operators, …)

9

Page 10: C# Language Overview Part II

Classes in C# – Classes in C# – ExamplesExamples

Example of classes:Example of classes: System.ConsoleSystem.Console System.StringSystem.String ( (stringstring in C#) in C#) System.Int32System.Int32 ( (intint in C#) in C#) System.ArraySystem.Array System.MathSystem.Math System.Random System.Random

10

Page 11: C# Language Overview Part II

Declaring ObjectsDeclaring Objects

An instance of a class or structure An instance of a class or structure can be defined like any other can be defined like any other variable:variable:

Instances cannot be used if they Instances cannot be used if they are are not initializednot initialized

11

using System;using System;......// Define two variables of type DateTime// Define two variables of type DateTimeDateTime today; DateTime today; DateTime halloween;DateTime halloween;

// Declare and initialize a structure instance// Declare and initialize a structure instanceDateTime today = DateTime.Now;DateTime today = DateTime.Now;

Page 12: C# Language Overview Part II

FieldsFields

Fields are data members of a classFields are data members of a class Can be variables and constantsCan be variables and constants Accessing a field doesn’t invoke Accessing a field doesn’t invoke

any actions of the objectany actions of the object Example:Example:

String.EmptyString.Empty (the (the """" string) string)

12

Page 13: C# Language Overview Part II

Accessing FieldsAccessing Fields

Constant fields can be only readConstant fields can be only read Variable fields can be read and Variable fields can be read and

modifiedmodified Usually properties are used instead Usually properties are used instead

of directly accessing variable fieldsof directly accessing variable fields Examples:Examples:

13

// Accessing read-only field// Accessing read-only fieldString empty = String.Empty;String empty = String.Empty;

// Accessing constant field// Accessing constant fieldint maxInt = Int32.MaxValue;int maxInt = Int32.MaxValue;

Page 14: C# Language Overview Part II

PropertiesProperties Properties look like fields (have name Properties look like fields (have name

and type), but they can contain code, and type), but they can contain code, executed when they are accessed executed when they are accessed

Usually used to control access to data Usually used to control access to data fields (wrappers), but can contain fields (wrappers), but can contain more complex logic more complex logic

Can have two components (and at Can have two components (and at least one of them) called least one of them) called accessorsaccessors getget for reading their value for reading their value

setset for changing their value for changing their value

14

Page 15: C# Language Overview Part II

Properties (2)Properties (2)

According to the implemented According to the implemented accessors properties can be:accessors properties can be: Read-only (Read-only (getget accessor only) accessor only) Read and write (both Read and write (both getget and and setset

accessors)accessors) Write-only (Write-only (setset accessor only) accessor only)

Example of read-only property: Example of read-only property: String.LengthString.Length

15

Page 16: C# Language Overview Part II

Accessing Properties and Accessing Properties and Fields – ExampleFields – Example

16

using System;using System;......DateTime christmas = new DateTime(2009, 12, DateTime christmas = new DateTime(2009, 12, 25);25);int day = christmas.Day;int day = christmas.Day;int month = christmas.Month;int month = christmas.Month;int year = christmas.Year;int year = christmas.Year;

Console.WriteLine(Console.WriteLine( "Christmas day: {0}, month: {1}, year: "Christmas day: {0}, month: {1}, year: {2}",{2}", day, month, year);day, month, year);

Console.WriteLine(Console.WriteLine( "Day of year: {0}", christmas.DayOfYear);"Day of year: {0}", christmas.DayOfYear);

Console.WriteLine("Is {0} leap year: {1}",Console.WriteLine("Is {0} leap year: {1}", year, DateTime.IsLeapYear(year));year, DateTime.IsLeapYear(year));

Page 17: C# Language Overview Part II

Instance and Static Instance and Static MembersMembers

Fields, properties and methods can be:Fields, properties and methods can be: InstanceInstance (or object members) (or object members) StaticStatic (or class members) (or class members)

InstanceInstance membersmembers are specific for each are specific for each objectobject Example: different dogs have different Example: different dogs have different

namename StaticStatic membersmembers are common for all are common for all

instances of a classinstances of a class Example: Example: DateTime.MinValueDateTime.MinValue is shared is shared

between all instances of between all instances of DateTimeDateTime17

Page 18: C# Language Overview Part II

Instance and Instance and Static Members Static Members

– Examples– Examples Example of instance memberExample of instance member

String.LengthString.Length Each string object has different Each string object has different

lengthlength

Example of static memberExample of static member Console.ReadLine()Console.ReadLine()

The console is only one (global for The console is only one (global for the program)the program)

Reading from the console does not Reading from the console does not require to create an instance of itrequire to create an instance of it

18

Page 19: C# Language Overview Part II

MethodsMethods

Methods manipulate the data of Methods manipulate the data of the object to which they belong or the object to which they belong or perform other tasksperform other tasks

Examples:Examples: Console.WriteLine(…)Console.WriteLine(…) Console.ReadLine()Console.ReadLine() String.Substring(index, length)String.Substring(index, length) Array.GetLength(index)Array.GetLength(index)

19

Page 20: C# Language Overview Part II

Instance MethodsInstance Methods

Instance methods manipulate the Instance methods manipulate the data of a specified object or data of a specified object or perform any other tasksperform any other tasks If a value is returned, it depends on If a value is returned, it depends on

the particular class instancethe particular class instance Syntax:Syntax:

The name of the instance, followed The name of the instance, followed by the name of the method, by the name of the method, separated by dotseparated by dot

20

<object_name>.<method_name>(<parameters>)<object_name>.<method_name>(<parameters>)

Page 21: C# Language Overview Part II

Calling Instance Methods – Calling Instance Methods – Examples Examples

Calling instance methods of Calling instance methods of StringString::

Calling instance methods of Calling instance methods of DateTimeDateTime::

21

String sampleLower = new String('a', 5);String sampleLower = new String('a', 5);String sampleUpper = sampleLower.ToUpper();String sampleUpper = sampleLower.ToUpper();

Console.WriteLine(sampleLower); // aaaaaConsole.WriteLine(sampleLower); // aaaaaConsole.WriteLine(sampleUpper); // AAAAAConsole.WriteLine(sampleUpper); // AAAAA

DateTime now = DateTime.Now;DateTime now = DateTime.Now;DateTime later = now.AddHours(8);DateTime later = now.AddHours(8);

Console.WriteLine("Now: {0}", now);Console.WriteLine("Now: {0}", now);Console.WriteLine("8 hours later: {0}", Console.WriteLine("8 hours later: {0}", later);later);

Page 22: C# Language Overview Part II

Static MethodsStatic Methods

Static methods are common for all Static methods are common for all instances of a class (shared instances of a class (shared between all instances)between all instances) Returned value depends only on the Returned value depends only on the

passed parameterspassed parameters No particular class instance is No particular class instance is

availableavailable Syntax:Syntax:

The name of the class, followed by The name of the class, followed by the name of the method, separated the name of the method, separated by dotby dot 22

<class_name>.<method_name>(<parameters>)<class_name>.<method_name>(<parameters>)

Page 23: C# Language Overview Part II

Calling Static Methods – Calling Static Methods – ExamplesExamples

23

using System;using System;

double radius = 2.9;double radius = 2.9;double area = Math.PI * Math.Pow(radius, 2);double area = Math.PI * Math.Pow(radius, 2);Console.WriteLine("Area: {0}", area);Console.WriteLine("Area: {0}", area);// Area: 26,4207942166902// Area: 26,4207942166902

double precise = 8.7654321;double precise = 8.7654321;double round3 = Math.Round(precise, 3);double round3 = Math.Round(precise, 3);double round1 = Math.Round(precise, 1);double round1 = Math.Round(precise, 1);Console.WriteLine(Console.WriteLine( "{0}; {1}; {2}", precise, round3, "{0}; {1}; {2}", precise, round3, round1);round1);// 8,7654321; 8,765; 8,8// 8,7654321; 8,765; 8,8

ConstaConstant fieldnt field

Static Static methometho

dd

Static Static methmeth

odod

Static Static methmeth

odod

Page 24: C# Language Overview Part II

ConstructorsConstructors Constructors are special methods Constructors are special methods

used to assign initial values of the used to assign initial values of the fields in an objectfields in an object Executed when an object of a given Executed when an object of a given

type is being createdtype is being created Have the same name as the class Have the same name as the class

that holds themthat holds them Do not return a valueDo not return a value

A class may have several A class may have several constructors with different set of constructors with different set of parametersparameters 24

Page 25: C# Language Overview Part II

Constructors (2)Constructors (2)

Constructor is invoked by the Constructor is invoked by the newnew operatoroperator

Examples:Examples:

25

String s = new String("Hello!"); // s = "Hello!"String s = new String("Hello!"); // s = "Hello!"

<instance_name> = new <class_name>(<parameters>)<instance_name> = new <class_name>(<parameters>)

String s = new String('*', 5); // s = "*****"String s = new String('*', 5); // s = "*****"

DateTime dt = new DateTime(2009, 12, 30);DateTime dt = new DateTime(2009, 12, 30);

DateTime dt = new DateTime(2009, 12, 30, 12, 33, DateTime dt = new DateTime(2009, 12, 30, 12, 33, 59);59);

Int32 value = new Int32(1024);Int32 value = new Int32(1024);

Page 26: C# Language Overview Part II

StructuresStructures Structures are similar to classesStructures are similar to classes Structures are usually used for storing Structures are usually used for storing

data structures, without any other data structures, without any other functionalityfunctionality

Structures can have fields, properties, etc.Structures can have fields, properties, etc. Using methods is not recommendedUsing methods is not recommended

Structures are Structures are value typesvalue types, and classes are , and classes are reference typesreference types (this will be discussed (this will be discussed later)later)

Example of structureExample of structure System.DateTimeSystem.DateTime – represents a date and – represents a date and

timetime26

Page 27: C# Language Overview Part II

What is a Namespace?What is a Namespace? Namespaces are used to organize the Namespaces are used to organize the

source code into more logical and source code into more logical and manageable waymanageable way

Namespaces can containNamespaces can contain Definitions of classes, structures, interfaces Definitions of classes, structures, interfaces

and other types and other namespacesand other types and other namespaces Namespaces can contain other namespacesNamespaces can contain other namespaces For example:For example:

SystemSystem namespace contains namespace contains DataData namespace namespace The name of the nested namespace is The name of the nested namespace is System.DataSystem.Data

27

Page 28: C# Language Overview Part II

Full Class NamesFull Class Names

A full name of a class is the name A full name of a class is the name of the class preceded by the name of the class preceded by the name of its namespaceof its namespace

Example:Example: ArrayArray class, defined in the class, defined in the SystemSystem

namespacenamespace The full name of the class is The full name of the class is System.ArraySystem.Array

28

<namespace_name>.<class_name><namespace_name>.<class_name>

Page 29: C# Language Overview Part II

Including NamespacesIncluding Namespaces The The usingusing directive in C#: directive in C#:

Allows using types in a namespace, Allows using types in a namespace, without specifying their full namewithout specifying their full name

Example:Example:

instead ofinstead of

29

using <namespace_name>using <namespace_name>

using System;using System;DateTime date;DateTime date;

System.DateTime date;System.DateTime date;

Page 30: C# Language Overview Part II

Common Type System Common Type System (CTS)(CTS)

CTS defines all data CTS defines all data typestypes supported in .NET Frameworksupported in .NET Framework Primitive types (e.g. Primitive types (e.g. intint, , floatfloat, , objectobject))

Classes (e.g. Classes (e.g. StringString, , ConsoleConsole, , ArrayArray)) Structures (e.g. Structures (e.g. DateTimeDateTime)) Arrays (e.g. Arrays (e.g. intint[][], , string[,]string[,])) Etc.Etc.

Object-oriented by designObject-oriented by design30

Page 31: C# Language Overview Part II

CTS and Different CTS and Different LanguagesLanguages

CTS is common for all .NET CTS is common for all .NET languageslanguages C#, VB.NET, J#, C#, VB.NET, J#, JScript.NETJScript.NET, ..., ...

CTS type mappings:CTS type mappings:

31

CTS TypeCTS Type C# TypeC# Type VB.NET TypeVB.NET Type

System.Int32System.Int32 intint IntegerInteger

System.SingleSystem.Single floatfloat SingleSingle

System.BooleanSystem.Boolean boolbool BooleanBoolean

System.StringSystem.String stringstring StringString

System.ObjectSystem.Object objectobject ObjectObject

Page 32: C# Language Overview Part II

Value and Reference Value and Reference TypesTypes

In CTS there are two categories of In CTS there are two categories of typestypes ValueValue typestypes Reference typesReference types

Placed in different areas of memoryPlaced in different areas of memory Value types live in the Value types live in the execution stackexecution stack

Freed when become out of scopeFreed when become out of scope

Reference types live in the Reference types live in the managed managed heap heap (dynamic memory)(dynamic memory) Freed by the Freed by the garbage collectorgarbage collector

32

Page 33: C# Language Overview Part II

Value and Reference Value and Reference Types – ExamplesTypes – Examples

Value typesValue types Most of the primitive typesMost of the primitive types StructuresStructures Examples: Examples: intint, , floatfloat, , boolbool, , DateTimeDateTime

Reference typesReference types Classes and interfacesClasses and interfaces StringsStrings ArraysArrays Examples: Examples: stringstring, , RandomRandom, , objectobject, , int[]int[]

33

Page 34: C# Language Overview Part II

Exceptions Exceptions HandlingHandlingThe Paradigm of Exceptions in The Paradigm of Exceptions in

OOPOOP

Page 35: C# Language Overview Part II

What are Exceptions?What are Exceptions? The exceptions in .NET Framework are The exceptions in .NET Framework are

classic implementation of the OOP classic implementation of the OOP exception modelexception model

Deliver powerful mechanism for Deliver powerful mechanism for centralized handling of errors and centralized handling of errors and unusual eventsunusual events

Substitute procedure-oriented approach, Substitute procedure-oriented approach, in which each function returns error codein which each function returns error code

Simplify code construction and Simplify code construction and maintenancemaintenance

Allow the problematic situations to be Allow the problematic situations to be processed at multiple levelsprocessed at multiple levels

35

Page 36: C# Language Overview Part II

Handling ExceptionsHandling Exceptions

In C# the exceptions can be In C# the exceptions can be handled by thehandled by the try-catch-finallytry-catch-finally constructionconstruction

catchcatch blocks can be used multiple blocks can be used multiple times to process different times to process different exception typesexception types 36

trytry{{ // Do some work that can raise an exception// Do some work that can raise an exception}}catch (SomeException)catch (SomeException){{ // Handle the caught exception// Handle the caught exception}}

Page 37: C# Language Overview Part II

Handling Exceptions – Handling Exceptions – ExampleExample

37

static void Main()static void Main(){{ string s = Console.ReadLine();string s = Console.ReadLine(); trytry {{ Int32.Parse(s);Int32.Parse(s); Console.WriteLine(Console.WriteLine( "You entered valid Int32 number {0}.", s);"You entered valid Int32 number {0}.", s); }} catchcatch (FormatException) (FormatException) {{ Console.WriteLine("Invalid integer number!");Console.WriteLine("Invalid integer number!"); }} catchcatch (OverflowException) (OverflowException) {{ Console.WriteLine(Console.WriteLine( "The number is too big to fit in Int32!");"The number is too big to fit in Int32!"); }}}}

Page 38: C# Language Overview Part II

TheThe System.ExceptionSystem.Exception ClassClass

Exceptions inExceptions in .NET .NET are objectsare objects TheThe System.ExceptionSystem.Exception class is base for class is base for

all exceptions in CLRall exceptions in CLR Contains information for the cause of Contains information for the cause of

the error or the unusual situationthe error or the unusual situation MessageMessage – – text description of the text description of the

exceptionexception

StackTraceStackTrace – – the snapshot of the stack at the snapshot of the stack at the moment of exception throwingthe moment of exception throwing

InnerExceptionInnerException – – exception caused the exception caused the currentcurrentexception exception ((if anyif any)) 38

Page 39: C# Language Overview Part II

Exception Properties – Exception Properties – ExampleExample

39

class ExceptionsTestclass ExceptionsTest{{ public static void CauseFormatException()public static void CauseFormatException() {{ string s = "an invalid number";string s = "an invalid number"; Int32.Parse(s);Int32.Parse(s); }} static void Main()static void Main() {{ trytry {{ CauseFormatException();CauseFormatException(); }} catch (FormatException fe)catch (FormatException fe) {{ Console.Error.WriteLine("Exception caught:Console.Error.WriteLine("Exception caught: {0}\n{1}", fe.Message, fe.StackTrace); {0}\n{1}", fe.Message, fe.StackTrace); }} }}}}

Page 40: C# Language Overview Part II

Exception PropertiesException Properties TheThe MessageMessage property gives brief property gives brief

description of the problemdescription of the problem TheThe StackTraceStackTrace property is extremely property is extremely

useful when identifying the reason useful when identifying the reason caused the exceptioncaused the exception

TheThe MessageMessage property gives brief property gives brief description of the problemdescription of the problem

TheThe StackTraceStackTrace property is extremely property is extremely useful when identifying the reason useful when identifying the reason caused the exceptioncaused the exception

40

Exception caught: Input string was not in a Exception caught: Input string was not in a correct format.correct format. at System.Number.ParseInt32(String s, at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)NumberStyles style, NumberFormatInfo info) at System.Int32.Parse(String s)at System.Int32.Parse(String s) at ExceptionsTest.CauseFormatException() in c:\at ExceptionsTest.CauseFormatException() in c:\consoleapplication1\exceptionstest.cs:line 8consoleapplication1\exceptionstest.cs:line 8 at ExceptionsTest.Main(String[] args) in c:\at ExceptionsTest.Main(String[] args) in c:\consoleapplication1\exceptionstest.cs:line 15consoleapplication1\exceptionstest.cs:line 15

Page 41: C# Language Overview Part II

Exception Properties Exception Properties (2)(2)

File names and line numbers are File names and line numbers are accessible only if the compilation was in accessible only if the compilation was in DebugDebug mode mode

When compiled in When compiled in ReleaseRelease mode, the mode, the information in the property information in the property StackTraceStackTrace is is quite different:quite different:

File names and line numbers are File names and line numbers are accessible only if the compilation was in accessible only if the compilation was in DebugDebug mode mode

When compiled in When compiled in ReleaseRelease mode, the mode, the information in the property information in the property StackTraceStackTrace is is quite different:quite different:

41

Exception caught: Input string was not in a Exception caught: Input string was not in a correct format.correct format. at System.Number.ParseInt32(String s, at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)NumberStyles style, NumberFormatInfo info) at ExceptionsTest.Main(String[] args)at ExceptionsTest.Main(String[] args)

Page 42: C# Language Overview Part II

Exception HierarchyException Hierarchy

Exceptions in .NET Framework are Exceptions in .NET Framework are organized in a hierarchyorganized in a hierarchy

42

Page 43: C# Language Overview Part II

Types of ExceptionsTypes of Exceptions All .NET exceptions inherit from All .NET exceptions inherit from System.ExceptionSystem.Exception

The system exceptions inherit from The system exceptions inherit from System.SystemExceptionSystem.SystemException, e.g., e.g. System.ArgumentExceptionSystem.ArgumentException

System.NullReferenceExceptionSystem.NullReferenceException

System.OutOfMemoryExceptionSystem.OutOfMemoryException

System.StackOverflowExceptionSystem.StackOverflowException

User-defined exceptions should inherit User-defined exceptions should inherit from from System.ApplicationExceptionSystem.ApplicationException

43

Page 44: C# Language Overview Part II

Handling ExceptionsHandling Exceptions

When catching an exception of a When catching an exception of a particular class, all its inheritors (child particular class, all its inheritors (child exceptions) are caught tooexceptions) are caught too

Example:Example:

HandlesHandles ArithmeticExceptionArithmeticException andand its its successorssuccessors DivideByZeroExceptionDivideByZeroException andand OverflowExceptionOverflowException

44

trytry{{ // Do some works that can raise an exception// Do some works that can raise an exception}}catch (System.ArithmeticException)catch (System.ArithmeticException){{ // Handle the caught arithmetic exception// Handle the caught arithmetic exception}}

Page 45: C# Language Overview Part II

Handling All ExceptionsHandling All Exceptions

All exceptions thrown by .NET All exceptions thrown by .NET managed code inherit the managed code inherit the System.ExceptionSystem.Exception exception exception

Unmanaged code can throw other Unmanaged code can throw other exceptionsexceptions

For handling all exceptions (even For handling all exceptions (even unmanaged) use the construction:unmanaged) use the construction:

45

trytry{{ // Do some works that can raise any exception// Do some works that can raise any exception}}catchcatch{{ // Handle the caught exception// Handle the caught exception}}

Page 46: C# Language Overview Part II

Throwing ExceptionsThrowing Exceptions

Exceptions are thrown (raised) by Exceptions are thrown (raised) by throwthrow keyword in C# keyword in C# Used to notify the calling code in Used to notify the calling code in

case of error or unusual situationcase of error or unusual situation When an exception is thrown:When an exception is thrown:

The program execution stopsThe program execution stops The exception travels over the stack The exception travels over the stack

until a suitable until a suitable catchcatch block is reached block is reached to handle itto handle it

Unhandled exceptions display error Unhandled exceptions display error messagemessage

46

Page 47: C# Language Overview Part II

How Exceptions Work?How Exceptions Work?

47

Main()Main()

Method 1Method 1

Method 2Method 2

Method NMethod N

2. Method call2. Method call

3. Method call3. Method call

4. Method call4. Method call……

Main()Main()

Method 1Method 1

Method 2Method 2

Method NMethod N

8. Find handler8. Find handler

7. Find handler7. Find handler

6. Find handler6. Find handler……

5. Throw an exception5. Throw an exception

.NET .NET CLRCLR

1. Execute the

1. Execute theprogramprogram 9. Find handler

9. Find handler

10. Display error message

10. Display error message

Page 48: C# Language Overview Part II

Using Using throwthrow Keyword Keyword Throwing an exception with error Throwing an exception with error

message:message:

Exceptions can take message and cause:Exceptions can take message and cause:

NoteNote:: if the original exception is not if the original exception is not passed the initial cause of the passed the initial cause of the exception is lostexception is lost 48

throw new ArgumentException("Invalid amount!");throw new ArgumentException("Invalid amount!");

trytry{{ Int32.Parse(str);Int32.Parse(str);}}catch (FormatException fe)catch (FormatException fe){{ throw new ArgumentException("Invalid number", throw new ArgumentException("Invalid number", fe);fe);}}

Page 49: C# Language Overview Part II

Throwing Exceptions – Throwing Exceptions – ExampleExample

49

public static double Sqrt(double value)public static double Sqrt(double value){{ if (value < 0)if (value < 0) throw new throw new System.ArgumentOutOfRangeException(System.ArgumentOutOfRangeException( "Sqrt for negative numbers is "Sqrt for negative numbers is undefined!");undefined!"); return Math.Sqrt(value);return Math.Sqrt(value);}}static void Main()static void Main(){{ trytry {{ Sqrt(-1);Sqrt(-1); }} catch (ArgumentOutOfRangeException ex)catch (ArgumentOutOfRangeException ex) {{ Console.Error.WriteLine("Error: " + Console.Error.WriteLine("Error: " + ex.Message);ex.Message); throw;throw; }}}}

Page 50: C# Language Overview Part II

Strings and Text Strings and Text ProcessingProcessing

Page 51: C# Language Overview Part II

What Is String?What Is String?

Strings are sequences of Strings are sequences of characterscharacters

Each character is a Unicode symbolEach character is a Unicode symbol Represented by the Represented by the stringstring data data

type in C# (type in C# (System.StringSystem.String)) Example:Example:

51

string s = "Hello, C#";string s = "Hello, C#";

HH ee ll ll oo ,, CC ##ss

Page 52: C# Language Overview Part II

The The System.StringSystem.String Class Class

Strings are represented by Strings are represented by System.StringSystem.String objects in .NET objects in .NET FrameworkFramework String objects contain an immutable String objects contain an immutable

(read-only) sequence of characters(read-only) sequence of characters Strings use Unicode in to support Strings use Unicode in to support

multiple languages and alphabetsmultiple languages and alphabets Strings are stored in the dynamic Strings are stored in the dynamic

memory (memory (managed heapmanaged heap)) System.StringSystem.String is reference type is reference type

52

Page 53: C# Language Overview Part II

The The System.StringSystem.String Class Class (2)(2)

String objects are like arrays of String objects are like arrays of characters (characters (char[]char[])) Have fixed length (Have fixed length (String.LengthString.Length)) Elements can be accessed directly Elements can be accessed directly

by indexby index The index is in the range [The index is in the range [00......Length-Length-11]]

53

string s = "Hello!";string s = "Hello!";int len = s.Length; // len = 6int len = s.Length; // len = 6char ch = s[1]; // ch = 'e'char ch = s[1]; // ch = 'e'

00 11 22 33 44 55

HH ee ll ll oo !!index = index =

s[index] = s[index] =

Page 54: C# Language Overview Part II

Strings – ExampleStrings – Example

54

static void Main()static void Main(){{ string s = string s = "Stand up, stand up, Balkan Superman.";"Stand up, stand up, Balkan Superman."; Console.WriteLine("s = \"{0}\"", s);Console.WriteLine("s = \"{0}\"", s); Console.WriteLine("s.Length = {0}", Console.WriteLine("s.Length = {0}", s.Length);s.Length); for (int i = 0; i < s.Length; i++)for (int i = 0; i < s.Length; i++) {{ Console.WriteLine("s[{0}] = {1}", i, Console.WriteLine("s[{0}] = {1}", i, s[i]);s[i]); }}}}

Page 55: C# Language Overview Part II

Declaring StringsDeclaring Strings

There are two ways of declaring There are two ways of declaring string variables:string variables: UsingUsing thethe C# C# keywordkeyword stringstring Using the .NET's fully qualified Using the .NET's fully qualified

class name class name System.StringSystem.String

The above three declarations are The above three declarations are equivalentequivalent

55

string str1;string str1;System.String str2;System.String str2;String str3;String str3;

Page 56: C# Language Overview Part II

Creating StringsCreating Strings

Before initializing a string variable Before initializing a string variable has has nullnull valuevalue

Strings can be initialized by:Strings can be initialized by: Assigning a string literal to the Assigning a string literal to the

string variablestring variable Assigning the value of another Assigning the value of another

string variablestring variable Assigning the result of operation of Assigning the result of operation of

type stringtype string

56

Page 57: C# Language Overview Part II

Creating Strings (2)Creating Strings (2) Not initialized variables has value of Not initialized variables has value of nullnull

Assigning a string literalAssigning a string literal

Assigning from another string Assigning from another string variablevariable

Assigning from the result of string Assigning from the result of string operationoperation

57

string s; // s is equal to nullstring s; // s is equal to null

string s = "I am a string literal!";string s = "I am a string literal!";

string s2 = s;string s2 = s;

string s = 42.ToString();string s = 42.ToString();

Page 58: C# Language Overview Part II

Reading and Printing Reading and Printing StringsStrings

Reading strings from the consoleReading strings from the console Use the method Use the method Console.Console.ReadLine()ReadLine()

58

string s = Console.ReadLine();string s = Console.ReadLine();

Console.Write("Please enter your name: "); Console.Write("Please enter your name: "); string name = Console.ReadLine();string name = Console.ReadLine();Console.Write("Hello, {0}! ", name);Console.Write("Hello, {0}! ", name);Console.WriteLine("Welcome to our party!");Console.WriteLine("Welcome to our party!");

Printing strings to the consolePrinting strings to the console Use the methods Write() and Use the methods Write() and

WriteLine()WriteLine()

Page 59: C# Language Overview Part II

Comparing StringsComparing Strings

A number of ways exist to compare A number of ways exist to compare two strings:two strings: Dictionary-based string comparisonDictionary-based string comparison

Case-insensitiveCase-insensitive

Case-sensitiveCase-sensitive

59

int result = string.Compare(str1, str2, true);int result = string.Compare(str1, str2, true);// result == 0 if str1 equals str2// result == 0 if str1 equals str2// result < 0 if str1 if before str2// result < 0 if str1 if before str2// result > 0 if str1 if after str2// result > 0 if str1 if after str2

string.Compare(str1, str2, false);string.Compare(str1, str2, false);

Page 60: C# Language Overview Part II

Comparing Strings – Comparing Strings – Example Example

Finding the first string in a Finding the first string in a lexicographical order from a given list lexicographical order from a given list of strings:of strings:

60

string[] towns = {"Sofia", "Varna", "Plovdiv",string[] towns = {"Sofia", "Varna", "Plovdiv","Pleven", "Bourgas", "Rousse", "Yambol"};"Pleven", "Bourgas", "Rousse", "Yambol"};

string firstTown = towns[0];string firstTown = towns[0];for (int i=1; i<towns.Length; i++)for (int i=1; i<towns.Length; i++){{ string currentTown = towns[i];string currentTown = towns[i]; if (String.Compare(currentTown, firstTown) < if (String.Compare(currentTown, firstTown) < 0)0) {{ firstTown = currentTown;firstTown = currentTown; }}}}Console.WriteLine("First town: {0}", firstTown);Console.WriteLine("First town: {0}", firstTown);

Page 61: C# Language Overview Part II

Concatenating StringsConcatenating Strings

There are two ways to combine There are two ways to combine strings:strings: Using the Using the Concat()Concat() method method

Using the Using the ++ or the or the +=+= operators operators

Any object can be appended to Any object can be appended to stringstring

61

string str = String.Concat(str1, str2); string str = String.Concat(str1, str2);

string str = str1 + str2 + str3;string str = str1 + str2 + str3;string str += str1;string str += str1;

string name = "Peter";string name = "Peter";int age = 22;int age = 22;string s = name + " " + age; // string s = name + " " + age; // "Peter 22" "Peter 22"

Page 62: C# Language Overview Part II

Searching in StringsSearching in Strings

Finding a character or substring Finding a character or substring within given stringwithin given string First occurrenceFirst occurrence

First occurrence starting at given First occurrence starting at given positionposition

Last occurrenceLast occurrence

62

IndexOf(string str)IndexOf(string str)

IndexOf(string str, int startIndex)IndexOf(string str, int startIndex)

LastIndexOf(string)LastIndexOf(string)

Page 63: C# Language Overview Part II

Searching in Strings – Searching in Strings – ExampleExample

63

string str = "C# Programming Course";string str = "C# Programming Course";int index = str.IndexOf("C#"); // index = 0int index = str.IndexOf("C#"); // index = 0index = str.IndexOf("Course"); // index = 15index = str.IndexOf("Course"); // index = 15index = str.IndexOf("COURSE"); // index = -1index = str.IndexOf("COURSE"); // index = -1// IndexOf is case-sensetive. -1 means not found// IndexOf is case-sensetive. -1 means not foundindex = str.IndexOf("ram"); // index = 7index = str.IndexOf("ram"); // index = 7index = str.IndexOf("r"); // index = 4index = str.IndexOf("r"); // index = 4index = str.IndexOf("r", 5); // index = 7index = str.IndexOf("r", 5); // index = 7index = str.IndexOf("r", 8); // index = 18index = str.IndexOf("r", 8); // index = 18

00 11 22 33 44 55 66 77 88 99 1010 1111 1212 1313 ……

CC ## PP rr oo gg rr aa mm mm ii nn gg ……index = index =

s[index] = s[index] =

Page 64: C# Language Overview Part II

Extracting SubstringsExtracting Substrings

Extracting substringsExtracting substrings str.Substring(int startIndex, int str.Substring(int startIndex, int length)length)

str.Substring(int startIndex)str.Substring(int startIndex)

64

string filename = @"C:\Pics\Rila2009.jpg";string filename = @"C:\Pics\Rila2009.jpg";string name = filename.Substring(8, 8);string name = filename.Substring(8, 8);// name is Rila2009// name is Rila2009

string filename = @"C:\Pics\Summer2009.jpg";string filename = @"C:\Pics\Summer2009.jpg";string nameAndExtension = filename.Substring(8);string nameAndExtension = filename.Substring(8);// nameAndExtension is Summer2009.jpg// nameAndExtension is Summer2009.jpg

00 11 22 33 44 55 66 77 88 99 1010 1111 1212 1313 1414 1515 1616 1717 1818 1919

CC :: \ \ PP ii cc ss \\ RR ii ll aa 22 00 00 55 .. jj pp gg

Page 65: C# Language Overview Part II

Splitting StringsSplitting Strings To split a string by given separator(s) To split a string by given separator(s)

use the following method:use the following method:

Example:Example:

65

string[] Split(params char[])string[] Split(params char[])

string listOfBeers =string listOfBeers = "Amstel, Zagorka, Tuborg, Becks.";"Amstel, Zagorka, Tuborg, Becks.";string[] beers = string[] beers = listOfBeers.Split(' ', ',', '.');listOfBeers.Split(' ', ',', '.');Console.WriteLine("Available beers are:");Console.WriteLine("Available beers are:");foreach (string beer in beers)foreach (string beer in beers){{ Console.WriteLine(beer);Console.WriteLine(beer);}}

Page 66: C# Language Overview Part II

Replacing and Deleting Replacing and Deleting SubstringsSubstrings

Replace(string,Replace(string, string)string) – replaces all – replaces all occurrences of given string with anotheroccurrences of given string with another The result is new string (strings are The result is new string (strings are

immutable)immutable)

ReRemovemove((indexindex,, lengthlength)) – deletes part of a – deletes part of a string and produces new string as resultstring and produces new string as result

66

string cocktail = "Vodka + Martini + Cherry";string cocktail = "Vodka + Martini + Cherry";string replaced = cocktail.Replace("+", "and");string replaced = cocktail.Replace("+", "and");// Vodka and Martini and Cherry// Vodka and Martini and Cherry

string price = "$ 1234567";string price = "$ 1234567";string lowPrice = price.Remove(2, 3);string lowPrice = price.Remove(2, 3);// $ 4567// $ 4567

Page 67: C# Language Overview Part II

Changing Character Changing Character CasingCasing

Using method Using method ToLower()ToLower()

Using method Using method ToUpper()ToUpper()

67

string alpha = "aBcDeFg";string alpha = "aBcDeFg";string lowerAlpha = alpha.ToLower(); // abcdefgstring lowerAlpha = alpha.ToLower(); // abcdefgConsole.WriteLine(lowerAlpha);Console.WriteLine(lowerAlpha);

string alpha = "aBcDeFg";string alpha = "aBcDeFg";string upperAlpha = alpha.ToUpper(); // ABCDEFGstring upperAlpha = alpha.ToUpper(); // ABCDEFGConsole.WriteLine(upperAlpha);Console.WriteLine(upperAlpha);

Page 68: C# Language Overview Part II

Trimming White SpaceTrimming White Space Using method Using method Trim()Trim()

Using method Using method Trim(charsTrim(chars))

Using Using TrimTrimStartStart()() and and TrimTrimEndEnd()()

68

string s = " example of white space ";string s = " example of white space ";string clean = s.Trim();string clean = s.Trim();Console.WriteLine(clean);Console.WriteLine(clean);

string s = " \t\nHello!!! \n";string s = " \t\nHello!!! \n";string clean = s.Trim(' ', ',' ,'!', '\n','\t');string clean = s.Trim(' ', ',' ,'!', '\n','\t');Console.WriteLine(clean); // HelloConsole.WriteLine(clean); // Hello

string s = " C# ";string s = " C# ";string clean = s.TrimStart(); // clean = "C# "string clean = s.TrimStart(); // clean = "C# "

Page 69: C# Language Overview Part II

Constructing StringsConstructing Strings

Strings are immutableStrings are immutable CConcat()oncat(), , RReplace()eplace(), , TTrim()rim(), ..., ...

return new string, do not modify return new string, do not modify the old onethe old one

Do not use "Do not use "++" for strings in a " for strings in a loop!loop! It runs very, very inefficiently!It runs very, very inefficiently!

69

public static string DupChar(char ch, int count)public static string DupChar(char ch, int count){{ string result = "";string result = ""; for (int i=0; i<count; i++)for (int i=0; i<count; i++) result += ch;result += ch; return result;return result;}}

Very bad Very bad practice. practice.

Avoid this!Avoid this!

Page 70: C# Language Overview Part II

Changing the Contents of Changing the Contents of a String – a String – StringBuilderStringBuilder

Use the Use the System.Text.StringBuilderSystem.Text.StringBuilder class for modifiable strings of class for modifiable strings of characters:characters:

Use Use StringBuilderStringBuilder if you need to if you need to keep adding characters to a stringkeep adding characters to a string

70

public static string ReverseString(string s)public static string ReverseString(string s){{ StringBuilder sb = new StringBuilder();StringBuilder sb = new StringBuilder(); for (int i = s.Length-1; i >= 0; i--)for (int i = s.Length-1; i >= 0; i--) sb.Append(s[i]);sb.Append(s[i]); return sb.ToString();return sb.ToString();}}

Page 71: C# Language Overview Part II

The The StringBuildeStringBuilder Classr Class

StringBuilderStringBuilder keeps a buffer keeps a buffer memory, allocated in advancememory, allocated in advance Most operations use the buffer Most operations use the buffer

memory and do not allocate new memory and do not allocate new objectsobjects

71

HH ee ll ll oo ,, CC ## !!StringBuilderStringBuilder::

LengthLength=9=9CapacityCapacity=15=15

CapacityCapacity

used used bufferbuffer((LengthLength))

unused unused bufferbuffer

Page 72: C# Language Overview Part II

StringBuilderStringBuilder – – ExampleExample

Extracting all capital letters from a Extracting all capital letters from a stringstring

72

public static string ExtractCapitals(string s)public static string ExtractCapitals(string s){{ StringBuilder result = new StringBuilder();StringBuilder result = new StringBuilder(); for (int i = 0; i<s.Length; i++) for (int i = 0; i<s.Length; i++) {{

if (Char.IsUpper(s[i]))if (Char.IsUpper(s[i])) {{ result.Append(s[i]);result.Append(s[i]); }} }} return result.ToString();return result.ToString();}}

Page 73: C# Language Overview Part II

Method Method ToString()ToString()

All classes have public virtual All classes have public virtual method method ToString()ToString() Returns a human-readable, culture-Returns a human-readable, culture-

sensitive string representing the sensitive string representing the objectobject

Most .NET Framework types have Most .NET Framework types have own implementation of own implementation of ToString()ToString() intint, , floatfloat, , boolbool, , DateTimeDateTime

73

int number = 5;int number = 5;string s = "The number is " + number.ToString();string s = "The number is " + number.ToString();Console.WriteLine(s); // The number is 5Console.WriteLine(s); // The number is 5

Page 74: C# Language Overview Part II

Method Method ToString(formatToString(format))

We can apply specific formatting We can apply specific formatting when converting objects to stringwhen converting objects to string ToString(foToString(forrmatString)matString) method method

74

int number = 42;int number = 42;string s = number.ToString("D5"); // 00042string s = number.ToString("D5"); // 00042

s = number.ToString("X"); // 2As = number.ToString("X"); // 2A

// Consider the default culture is Bulgarian// Consider the default culture is Bulgarians = number.ToString("C"); // 42,00 лвs = number.ToString("C"); // 42,00 лв

double d = 0.375;double d = 0.375;s = d.ToString("P2"); // 37,50 %s = d.ToString("P2"); // 37,50 %

Page 75: C# Language Overview Part II

Formatting StringsFormatting Strings The formatting strings are different The formatting strings are different

for the different typesfor the different types Some formatting strings for numbers:Some formatting strings for numbers:

DD – number (for integer types) – number (for integer types)

CC – currency (according to current – currency (according to current culture)culture)

EE – number in exponential notation – number in exponential notation

PP – percentage – percentage

XX – hexadecimal number – hexadecimal number

FF – fixed point (for real numbers) – fixed point (for real numbers)75

Page 76: C# Language Overview Part II

Method Method String.Format()String.Format()

Applies Applies templatestemplates for formatting for formatting stringsstrings Placeholders are used for dynamic Placeholders are used for dynamic

texttext Like Like Console.WriteLine(…)Console.WriteLine(…)

76

string template = "If I were {0}, I would {1}.";string template = "If I were {0}, I would {1}.";string sentence1 = String.Format(string sentence1 = String.Format( template, "developer", "know C#");template, "developer", "know C#");Console.WriteLine(sentence1);Console.WriteLine(sentence1);// If I were developer, I would know C#.// If I were developer, I would know C#.

string sentence2 = String.Format(string sentence2 = String.Format( template, "elephant", "weigh 4500 kg");template, "elephant", "weigh 4500 kg");Console.WriteLine(sentence2);Console.WriteLine(sentence2);// If I were elephant, I would weigh 4500 kg.// If I were elephant, I would weigh 4500 kg.

Page 77: C# Language Overview Part II

Composite FormattingComposite Formatting The placeholders in the composite The placeholders in the composite

formatting strings are specified as formatting strings are specified as follows:follows:

Examples:Examples:

77

{index[,alignment][:formatString]}{index[,alignment][:formatString]}

double d = 0.375;double d = 0.375;s = String.Format("{0,10:F5}", d);s = String.Format("{0,10:F5}", d);// s = " 0,37500"// s = " 0,37500"

int number = 42;int number = 42;Console.WriteLine("Dec {0:D} = Hex {1:X}",Console.WriteLine("Dec {0:D} = Hex {1:X}", number, number);number, number);// Dec 42 = Hex 2A// Dec 42 = Hex 2A

Page 78: C# Language Overview Part II

Formatting DatesFormatting Dates

Dates have their own formatting Dates have their own formatting stringsstrings dd, , dddd – – day (with/without leading day (with/without leading

zero)zero) MM, , MMMM – – monthmonth yyyy, , yyyyyyyy – – year (2 or 4 digits)year (2 or 4 digits) hh, , HHHH, , mm, , mmmm, , ss, , ssss – – hour, minute, hour, minute,

secondsecond

78

DateTime now = DateTime.Now;DateTime now = DateTime.Now;Console.WriteLine(Console.WriteLine( "Now is {0:d.MM.yyyy HH:mm:ss}", now);"Now is {0:d.MM.yyyy HH:mm:ss}", now);// Now is 31.11.2009 11:30:32// Now is 31.11.2009 11:30:32

Page 79: C# Language Overview Part II

Collection Collection ClassesClassesLists, Trees, DictionariesLists, Trees, Dictionaries

Page 80: C# Language Overview Part II

What are Generics?What are Generics? Generics allow defining parameterized Generics allow defining parameterized

classes that process data of unknown classes that process data of unknown (generic) type(generic) type The class can be instantiated with The class can be instantiated with

several different particular typesseveral different particular types Example: Example: List<T>List<T> List<int>List<int> / / List<string>List<string> / / List<Student>List<Student>

Generics are also known as Generics are also known as ""parameterizedparameterized typestypes" or "" or "template template typestypes"" Similar to the templates in C++Similar to the templates in C++ Similar to the generics in JavaSimilar to the generics in Java 80

Page 81: C# Language Overview Part II

The The List<T>List<T> Class Class Implements the abstract data Implements the abstract data

structure structure listlist using an array using an array All elements are of the same type All elements are of the same type TT TT can be any type, e.g. can be any type, e.g. List<int>List<int>, , List<string>List<string>, , List<DateTime>List<DateTime>

Size is dynamically increased as Size is dynamically increased as neededneeded

Basic functionality:Basic functionality: CountCount – returns the number of elements – returns the number of elements Add(T)Add(T) – appends given element at the – appends given element at the

endend81

Page 82: C# Language Overview Part II

List<T>List<T> – Simple – Simple ExampleExample

82

static void Main()static void Main(){{ List<string> list = new List<string>();List<string> list = new List<string>();

list.Add("C#");list.Add("C#"); list.Add("Java");list.Add("Java"); list.Add("PHP");list.Add("PHP");

foreach (string item in list)foreach (string item in list) {{ Console.WriteLine(item);Console.WriteLine(item); }}

// Result:// Result: // C#// C# // Java// Java // PHP// PHP}}

Page 83: C# Language Overview Part II

List<T>List<T> – Functionality – Functionality list[index]list[index] – access element by index – access element by index Insert(indexInsert(index,, T)T) – inserts given – inserts given

element to the list at a specified element to the list at a specified positionposition

Remove(T)Remove(T) – removes the first – removes the first occurrence of given elementoccurrence of given element

RemoveAt(index)RemoveAt(index) – removes the element – removes the element at the specified positionat the specified position

Clear()Clear() – removes all elements – removes all elements Contains(TContains(T)) – determines whether an – determines whether an

element is part of the listelement is part of the list83

Page 84: C# Language Overview Part II

List<T>List<T> – Functionality – Functionality (2)(2)

IndexOf()IndexOf() – returns the index of the – returns the index of the first occurrence of a valuefirst occurrence of a value in the list in the list ((zero-basedzero-based))

Reverse()Reverse() – reverses the order of the – reverses the order of the elements in the list or a portion of itelements in the list or a portion of it

Sort()Sort() – sorts the elements in the list – sorts the elements in the list or a portion of itor a portion of it

ToArray()ToArray() – converts the elements of – converts the elements of the list to an arraythe list to an array

TrimExcess()TrimExcess() – sets the capacity to – sets the capacity to the actual number of elementsthe actual number of elements 84

Page 85: C# Language Overview Part II

Primes in an Interval – Primes in an Interval – ExampleExample

85

static List<int> FindPrimes(int start, int end)static List<int> FindPrimes(int start, int end){{ List<int> primesList = new List<int>();List<int> primesList = new List<int>();

for (int num = start; num <= end; num++)for (int num = start; num <= end; num++) {{ bool prime = true;bool prime = true; for (int div = 2; div <= Math.Sqrt(num); for (int div = 2; div <= Math.Sqrt(num); div++)div++) {{ if (num % div == 0)if (num % div == 0) {{ prime = false;prime = false; break;break; }} }} if (prime)if (prime) {{ primesList.Add(num);primesList.Add(num); }} }} return primesList;return primesList;}}

Page 86: C# Language Overview Part II

The The Stack<T>Stack<T> Class Class Implements the Implements the stackstack data structure data structure

using an arrayusing an array Elements are of the same type Elements are of the same type TT TT can be any type, e.g. can be any type, e.g. Stack<int>Stack<int> Size is dynamically increased as Size is dynamically increased as

neededneeded Basic functionality:Basic functionality:

Push(T)Push(T) – inserts elements to the – inserts elements to the stackstack

Pop()Pop() – removes and returns the top – removes and returns the top element from the stackelement from the stack 86

Page 87: C# Language Overview Part II

Stack<T>Stack<T> – Example – Example

Using Using Push()Push(), , Pop()Pop() and and Peek()Peek() methodsmethods

87

static void Main()static void Main(){{ Stack<string> stack = new Stack<string>();Stack<string> stack = new Stack<string>();

stack.Push("1. Ivan");stack.Push("1. Ivan"); stack.Push("2. Nikolay");stack.Push("2. Nikolay"); stack.Push("3. Maria");stack.Push("3. Maria"); stack.Push("4. George");stack.Push("4. George");

Console.WriteLine("Top = {0}", stack.Peek());Console.WriteLine("Top = {0}", stack.Peek());

while (stack.Count > 0)while (stack.Count > 0) {{ string personName = stack.Pop();string personName = stack.Pop(); Console.WriteLine(personName);Console.WriteLine(personName); }}}}

Page 88: C# Language Overview Part II

The The Queue<T>Queue<T> Class Class Implements the queue data structure Implements the queue data structure

using a circular resizable arrayusing a circular resizable array Elements are from the same type Elements are from the same type TT TT can be any type, e.g. can be any type, e.g. Stack<int>Stack<int> Size is dynamically increased as Size is dynamically increased as

neededneeded Basic functionality:Basic functionality:

Enqueue(T)Enqueue(T) – adds an element to the – adds an element to theend of the queueend of the queue

Dequeue()Dequeue() – removes and returns the – removes and returns the element at the beginning of the queueelement at the beginning of the queue

88

Page 89: C# Language Overview Part II

Queue<T>Queue<T> – – ExampleExample Using Using Enqueue()Enqueue() and and Dequeue()Dequeue() methods methods

89

static void Main()static void Main(){{ Queue<string> queue = new Queue<string>();Queue<string> queue = new Queue<string>();

queue.Enqueue("Message One");queue.Enqueue("Message One"); queue.Enqueue("Message Two");queue.Enqueue("Message Two"); queue.Enqueue("Message Three");queue.Enqueue("Message Three"); queue.Enqueue("Message Four");queue.Enqueue("Message Four");

while (queue.Count > 0)while (queue.Count > 0) {{ string message = queue.Dequeue();string message = queue.Dequeue(); Console.WriteLine(message);Console.WriteLine(message); }}}}

Page 90: C# Language Overview Part II

Dictionary<TKey,TValue>Dictionary<TKey,TValue> ClassClass

Implements the abstract data type Implements the abstract data type ""DictionaryDictionary" as hash table" as hash table Size is dynamically increased as neededSize is dynamically increased as needed Contains a collection of key-and-value Contains a collection of key-and-value

pairs arranged by the hash code of the pairs arranged by the hash code of the key – h(key) = valuekey – h(key) = value

Collisions are resolved by chainingCollisions are resolved by chaining Dictionary<TKey,TValue>Dictionary<TKey,TValue> class relies on class relies on

Object.Object.Equals(Equals()) method for method for comparing elementscomparing elements

90

Page 91: C# Language Overview Part II

Dictionary<TKey,TValue>Dictionary<TKey,TValue> Class (2)Class (2)

Object.GetHashCode()Object.GetHashCode() method for method for calculating the hash codes of the calculating the hash codes of the elementselements

Major operations:Major operations: Add(TKey,TValue)Add(TKey,TValue) – adds an element – adds an element

with the specified key and value into with the specified key and value into the the dictionarydictionary

Remove(TKey)Remove(TKey) – removes the element – removes the element with the specified key with the specified key

Clear()Clear() – removes all elements – removes all elements this[]this[] – returns element by key – returns element by key 91

Page 92: C# Language Overview Part II

Dictionary<TKey,TValue>Dictionary<TKey,TValue> Class (3)Class (3)

CountCount – returns the number of elements – returns the number of elements ContainsKey(TKey)ContainsKey(TKey) – determines whether – determines whether

the dictionary contains given keythe dictionary contains given key ContainsValue(TValue)ContainsValue(TValue) – determines – determines

whether the dictionary contains given whether the dictionary contains given valuevalue

KeysKeys – returns a collection of the keys – returns a collection of the keys ValuesValues – returns a collection of the values – returns a collection of the values TryGetValue(TKey,out TValueTryGetValue(TKey,out TValue)) – if the key – if the key

is found, returns it in the is found, returns it in the TValueTValue, , otherwise returns the default value for otherwise returns the default value for the the TValueTValue type type

92

Page 93: C# Language Overview Part II

Dictionary<TKey,Tvalue>Dictionary<TKey,Tvalue> – – ExampleExample

93

Dictionary<string, int> studentsMarks Dictionary<string, int> studentsMarks = new Dictionary<string, int>(); = new Dictionary<string, int>();studentsMarks.Add("Ivan", 4);studentsMarks.Add("Ivan", 4);studentsMarks.Add("Peter", 6);studentsMarks.Add("Peter", 6);studentsMarks.Add("Maria", 6);studentsMarks.Add("Maria", 6);studentsMarks.Add("George", 5);studentsMarks.Add("George", 5);int peterMark = studentsMarks["Peter"];int peterMark = studentsMarks["Peter"];

Console.WriteLine("Peter's mark: {0}", peterMark);Console.WriteLine("Peter's mark: {0}", peterMark);Console.WriteLine("Is Peter in the hash table: {0}",Console.WriteLine("Is Peter in the hash table: {0}", studentsMarks.ContainsKey("Peter"));studentsMarks.ContainsKey("Peter"));Console.WriteLine("Students and grades:");Console.WriteLine("Students and grades:");

foreach (var pair in studentsMarks)foreach (var pair in studentsMarks){{ Console.WriteLine("{0} --> {1} ", pair.Key, Console.WriteLine("{0} --> {1} ", pair.Key, pair.Value);pair.Value);}}

Page 94: C# Language Overview Part II

Counting Words in Counting Words in Given TextGiven Text

94

string text = "Welcome to our C# course. In this " +string text = "Welcome to our C# course. In this " + "course you will learn how to write simple " +"course you will learn how to write simple " + "programs in C# and Microsoft .NET";"programs in C# and Microsoft .NET";string[] words = text.Split(new char[] {' ', ',', string[] words = text.Split(new char[] {' ', ',', '.'},'.'}, StringSplitOptions.RemoveEmptyEntries);StringSplitOptions.RemoveEmptyEntries);var wordsCount = new Dictionary<string, int>();var wordsCount = new Dictionary<string, int>();

foreach (string word in words)foreach (string word in words){{ if (wordsCount.ContainsKey(word))if (wordsCount.ContainsKey(word)) wordsCount[word]++;wordsCount[word]++; elseelse wordsCount.Add(word, 1);wordsCount.Add(word, 1);}}

foreach (var pair in wordsCount)foreach (var pair in wordsCount){{ Console.WriteLine("{0} --> {1}", pair.Key, Console.WriteLine("{0} --> {1}", pair.Key, pair.Value);pair.Value);}}

Page 95: C# Language Overview Part II

Balanced Trees in .NETBalanced Trees in .NET Balanced Binary Search TreesBalanced Binary Search Trees

Ordered binary search trees that have Ordered binary search trees that have height of height of loglog22(n)(n) where where nn is the number of is the number of their nodestheir nodes

Searching costs about Searching costs about loglog22(n)(n) comparisons comparisons

.NET Framework has built-in .NET Framework has built-in implementations of balanced search trees, implementations of balanced search trees, e.g.:e.g.: SortedDictionary<K,V>SortedDictionary<K,V>

Red-black tree based map of key-value pairsRed-black tree based map of key-value pairs

External libraries like "Wintellect Power External libraries like "Wintellect Power Collections for .NET" are more flexibleCollections for .NET" are more flexible

95

Page 96: C# Language Overview Part II

Sorted Dictionary – Sorted Dictionary – Example Example

96

string text = "Welcome to our C# course. In this " +string text = "Welcome to our C# course. In this " + "course you will learn how to write simple " +"course you will learn how to write simple " + "programs in C# and Microsoft .NET";"programs in C# and Microsoft .NET";string[] words = text.Split(new char[] {' ', ',', string[] words = text.Split(new char[] {' ', ',', '.'},'.'}, StringSplitOptions.RemoveEmptyEntries);StringSplitOptions.RemoveEmptyEntries);var wordsCount = new SortedDictionary<string, int>();var wordsCount = new SortedDictionary<string, int>();

foreach (string word in words)foreach (string word in words){{ if (wordsCount.ContainsKey(word))if (wordsCount.ContainsKey(word)) wordsCount[word]++;wordsCount[word]++; elseelse wordsCount.Add(word, 1);wordsCount.Add(word, 1);}}

foreach (var pair in wordsCount)foreach (var pair in wordsCount){{ Console.WriteLine("{0} --> {1}", pair.Key, Console.WriteLine("{0} --> {1}", pair.Key, pair.Value);pair.Value);}}

Page 97: C# Language Overview Part II

AttributesAttributesWhat They Are? How and When to What They Are? How and When to Use Them?Use Them?

Page 98: C# Language Overview Part II

What Are Attributes?What Are Attributes? Special declarative tags for Special declarative tags for

attaching descriptive informationattaching descriptive information ((annotationsannotations) ) to the declarations in to the declarations in the codethe code

At compile time attributes are saved At compile time attributes are saved in the assembly's metadatain the assembly's metadata

Can be extracted from the metadata Can be extracted from the metadata and can be manipulated by different and can be manipulated by different toolstools

Instances of classes derived from Instances of classes derived from System.AttributeSystem.Attribute 98

Page 99: C# Language Overview Part II

Attributes Applying – Attributes Applying – ExampleExample

Attribute's name is surrounded by Attribute's name is surrounded by square brackets and is placed before square brackets and is placed before the declaration which it refers to:the declaration which it refers to:

[Flags][Flags] attribute indicates that the attribute indicates that the enumenum type can be treated type can be treated like a set of like a set of bit flagsbit flags

Attribute's name is surrounded by Attribute's name is surrounded by square brackets and is placed before square brackets and is placed before the declaration which it refers to:the declaration which it refers to:

[Flags][Flags] attribute indicates that the attribute indicates that the enumenum type can be treated type can be treated like a set of like a set of bit flagsbit flags

99

[Flags] // System.FlagsAttribute[Flags] // System.FlagsAttributepublic enum FileAccess public enum FileAccess {{ Read = 1,Read = 1, Write = 2,Write = 2, ReadWrite = Read | WriteReadWrite = Read | Write}}

Page 100: C# Language Overview Part II

Attributes With Attributes With ParametersParameters

Attributes use parameters for Attributes use parameters for initialization:initialization:

In the example the In the example the [[DllImportDllImport]] attribute isattribute is instantiated by the instantiated by the compilercompiler as followsas follows:: An object of An object of System.Runtime. System.Runtime. InteropServices.DllImportAttributeInteropServices.DllImportAttribute class is created and initializedclass is created and initialized

100

[DllImport("user32.dll", EntryPoint="MessageBox")][DllImport("user32.dll", EntryPoint="MessageBox")]public static extern int ShowMessageBox(int hWnd,public static extern int ShowMessageBox(int hWnd, string text, string caption, int type);string text, string caption, int type);......ShowMessageBox(0, "Some text", "Some caption", 0);ShowMessageBox(0, "Some text", "Some caption", 0);

Page 101: C# Language Overview Part II

C# Language OverviewC# Language Overview(Part II)(Part II)

Questions?Questions?

http://academy.telerik.com