8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
1/101
C# Language Overview(Part II)
Creating and Using Objects, Exceptions, Strings,Generics, Collections, Attributes
Doncho Minkov
Telerik School Academy
schoolacademy.telerik.com
Technical Trainerhttp://www.minkov.it
http://schoolacademy.telerik.com/http://minkov.it/http://minkov.it/http://schoolacademy.telerik.com/http://schoolacademy.telerik.com/8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
2/101
Table of Contents
1. Creating and Using Objects
2. Exceptions Handling
3. Strings and Text Processing
4. Generics
5. Collection Classes
6. Attributes
2
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
3/101
Using Classes and ObjectsUsing the Standard .NET Framework Classes
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
4/101
What is Class?
The formal definition of class:
Definition by Google
4
Classes act as templates from which aninstance of an object is created at run
time. Classes define the properties of theobject and the methods used to controlthe object's behavior.
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
5/101
Classes
Classes provide the structure for objects
Define their prototype, act as template
Classes define:
Set of attributes
Represented by fields and properties
Hold their state
Set of actions (behavior) Represented by methods
A class defines the methods and types of data
associated with an object 5
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
6/101
Classes Example
6
Account
+Owner: Person+Ammount: double
+Suspend()
+Deposit(sum:double)+Withdraw(sum:double)
Class Name Attributes
(Properties
and Fields)
Operations
(Methods)
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
7/101
Objects
An objectis a concrete instanceof a particularclass
Creating an object from a class is calledinstantiation
Objects have state
Set of values associated to their attributes
Example:
Class: Account
Objects: Ivan's account, Peter's account
7
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
8/101
Objects Example
8
Account
+Owner: Person+Ammount: double
+Suspend()
+Deposit(sum:double)
+Withdraw(sum:double)
Class ivanAccount+Owner="Ivan Kolev"
+Ammount=5000.0
peterAccount
+Owner="Peter Kirov"
+Ammount=1825.33
kirilAccount
+Owner="Kiril Kirov"
+Ammount=25.0
Object
Object
Object
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
9/101
Classes in C#
Basic units that compose programs
Implementation is encapsulated(hidden)
Classes in C# can contain:
Fields (member variables)
Properties
Methods
Constructors
Inner types
Etc. (events, indexers, operators, ) 9
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
10/101
Classes in C# Examples
Example of classes:
System.Console
System.String(stringin C#)
System.Int32(intin C#) System.Array
System.Math
System.Random
10
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
11/101
Declaring Objects
An instance of a class or structure can bedefined like any other variable:
Instances cannot be used if they are
not initialized
11
using System;
...
// Define two variables of type DateTimeDateTime today;
DateTime halloween;
// Declare and initialize a structure instanceDateTime today = DateTime.Now;
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
12/101
Fields
Fields are data members of a class
Can be variables and constants
Accessing a field doesnt invoke any actions of
the object Example:
String.Empty(the ""string)
12
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
13/101
Accessing Fields
Constant fields can be only read
Variable fields can be read and modified
Usually properties are used instead of directly
accessing variable fields Examples:
13
// Accessing read-only field
String empty = String.Empty;
// Accessing constant fieldint maxInt = Int32.MaxValue;
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
14/101
Properties
Properties look like fields (have name and
type), but they can contain code, executedwhen they are accessed
Usually used to control access to data
fields (wrappers), but can contain morecomplex logic
Can have two components (and at least oneof them) called accessors
getfor reading their value
setfor changing their value14
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
15/101
Properties (2)
According to the implemented accessorsproperties can be:
Read-only (getaccessor only)
Read and write (both getand setaccessors) Write-only (setaccessor only)
Example of read-only property:
String.Length
15
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
16/101
Accessing Properties and Fields Example
16
using System;...DateTime christmas = new DateTime(2009, 12, 25);int day = christmas.Day;int month = christmas.Month;
int year = christmas.Year;
Console.WriteLine("Christmas day: {0}, month: {1}, year: {2}",day, month, year);
Console.WriteLine("Day of year: {0}", christmas.DayOfYear);
Console.WriteLine("Is {0} leap year: {1}",year, DateTime.IsLeapYear(year));
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
17/101
Instance and Static Members
Fields, properties and methods can be:
Instance(or object members)
Static(or class members)
Instancemembersare specific for each object Example: different dogs have different name
Staticmembersare common for all instances
of a class
Example: DateTime.MinValueis sharedbetween all instances of DateTime
17
d i
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
18/101
Instance and StaticMembers Examples
Example of instance member String.Length
Each string object has different length
Example of static member
Console.ReadLine()
The console is only one (global for the program)
Reading from the console does not require tocreate an instance of it
18
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
19/101
Methods
Methods manipulate the data of the object towhich they belong or perform other tasks
Examples:
Console.WriteLine() Console.ReadLine()
String.Substring(index, length)
Array.GetLength(index)
19
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
20/101
Instance Methods
Instance methods manipulate the data of aspecified object or perform any other tasks
If a value is returned, it depends on theparticular class instance
Syntax:
The name of the instance, followed by the
name of the method, separated by dot
20
.()
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
21/101
Calling Instance Methods Examples
Calling instance methods of String:
Calling instance methods of DateTime:
21
String sampleLower = new String('a', 5);String sampleUpper = sampleLower.ToUpper();
Console.WriteLine(sampleLower); // aaaaa
Console.WriteLine(sampleUpper); // AAAAA
DateTime now = DateTime.Now;DateTime later = now.AddHours(8);
Console.WriteLine("Now: {0}", now);Console.WriteLine("8 hours later: {0}", later);
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
22/101
Static Methods
Static methods are common for all instances ofa class (shared between all instances)
Returned value depends only on the passedparameters
No particular class instance is available
Syntax:
The name of the class, followed by the name ofthe method, separated by dot
22
.()
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
23/101
Calling Static Methods Examples
23
using System;
double radius = 2.9;double area = Math.PI * Math.Pow(radius, 2);Console.WriteLine("Area: {0}", area);
// Area: 26,4207942166902
double precise = 8.7654321;double round3 = Math.Round(precise, 3);double round1 = Math.Round(precise, 1);Console.WriteLine(
"{0}; {1}; {2}", precise, round3, round1);// 8,7654321; 8,765; 8,8
Constantfield Staticmethod
Staticmethod
Staticmethod
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
24/101
Constructors
Constructors are special methods used toassign initial values of the fields in an object
Executed when an object of a given type isbeing created
Have the same name as the class that holdsthem
Do not return a value
A class may have several constructors withdifferent set of parameters
24
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
25/101
Constructors (2)
Constructor is invoked by the newoperator
Examples:
25
String s = new String("Hello!"); // s = "Hello!"
= new ()
String s = new String('*', 5); // s = "*****"
DateTime dt = new DateTime(2009, 12, 30);
DateTime dt = new DateTime(2009, 12, 30, 12, 33, 59);
Int32 value = new Int32(1024);
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
26/101
Structures
Structures are similar to classes
Structures are usually used for storing datastructures, without any other functionality
Structures can have fields, properties, etc. Using methods is not recommended
Structures are value types, and classes are
reference types(this will be discussed later) Example of structure
System.DateTimerepresents a date and time26
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
27/101
What is a Namespace?
Namespaces are used to organize the source
code into more logical and manageable way
Namespaces can contain
Definitions of classes, structures, interfaces andother types and other namespaces
Namespaces can contain other namespaces
For example: Systemnamespace contains Datanamespace
The name of the nested namespace is
System.Data 27
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
28/101
Full Class Names
A full name of a class is the name of the classpreceded by the name of its namespace
Example: Arrayclass, defined in the Systemnamespace
The full name of the class is System.Array
28
.
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
29/101
Including Namespaces
The usingdirective in C#:
Allows using types in a namespace, without
specifying their full nameExample:
instead of
29
using
using System;
DateTime date;
System.DateTime date;
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
30/101
Common Type System (CTS)
CTS defines all data typessupported in .NETFramework
Primitive types (e.g. int, float, object)
Classes (e.g. String, Console, Array)
Structures (e.g. DateTime)
Arrays (e.g. int[], string[,])
Etc.
Object-oriented by design
30
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
31/101
CTS and Different Languages
CTS is common for all .NET languages
C#, VB.NET, J#, JScript.NET, ...
CTS type mappings:
31
CTS Type C# Type VB.NET Type
System.Int32 int Integer
System.Single float Single
System.Boolean bool Boolean
System.String string String
System.Object object Object
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
32/101
Value and Reference Types
In CTS there are two categories of types
Valuetypes Reference types
Placed in different areas of memory Value types live in the execution stack
Freed when become out of scope
Reference types live in the managed heap(dynamic memory)
Freed by the garbage collector
32
Value and Reference Types
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
33/101
Value and Reference Types Examples
Value types
Most of the primitive types
Structures
Examples: int, float, bool, DateTime Reference types
Classes and interfaces
Strings
Arrays
Examples: string, Random, object, int[] 33
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
34/101
Exceptions HandlingThe Paradigm of Exceptions in OOP
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
35/101
What are Exceptions?
The exceptions in .NET Framework are classicimplementation of the OOP exception model
Deliver powerful mechanism for centralizedhandling of errors and unusual events
Substitute procedure-oriented approach,in which each function returns error code
Simplify code construction and maintenance Allow the problematic situations to be
processed at multiple levels
35
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
36/101
Handling Exceptions
In C# the exceptions can be handled by the
try-catch-finallyconstruction
catchblocks can be used multiple times toprocess different exception types
36
try{
// Do some work that can raise an exception}catch (SomeException){
// Handle the caught exception}
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
37/101
Handling Exceptions Example
37
static void Main(){
string s = Console.ReadLine();try{
Int32.Parse(s);Console.WriteLine(
"You entered valid Int32 number {0}.", s);}catch(FormatException){
Console.WriteLine("Invalid integer number!");}
catch(OverflowException){
Console.WriteLine("The number is too big to fit in Int32!");
}}
h i l
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
38/101
The System.ExceptionClass
Exceptions in .NET are objects
The System.Exceptionclass is base for allexceptions in CLR
Contains information for the cause of the erroror the unusual situation
Messagetext description of the exception
StackTracethe snapshot of the stack at themoment of exception throwing
InnerExceptionexception caused the currentexception (if any)
38
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
39/101
Exception Properties Example
39
class ExceptionsTest
{ public static void CauseFormatException(){
string s = "an invalid number";Int32.Parse(s);
}static void Main(){
try{
CauseFormatException();}catch (FormatException fe)
{Console.Error.WriteLine("Exception caught:{0}\n{1}", fe.Message, fe.StackTrace);
}}
}
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
40/101
E i P i ( )
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
41/101
Exception Properties (2)
File names and line numbers are accessible only if the
compilation was in Debugmode
When compiled in Releasemode, the information inthe property StackTraceis quite different:
41
Exception caught: Input string was not in a correctformat.
at System.Number.ParseInt32(String s, NumberStylesstyle, NumberFormatInfo info)
at ExceptionsTest.Main(String[] args)
E i Hi h
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
42/101
Exception Hierarchy
Exceptions in .NET Framework are organizedin a hierarchy
42
T f E i
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
43/101
Types of Exceptions
All .NET exceptions inherit from System.Exception
The system exceptions inherit from
System.SystemException, e.g.
System.ArgumentException
System.NullReferenceException
System.OutOfMemoryException
System.StackOverflowException
User-defined exceptions should inherit fromSystem.ApplicationException
43
H dli E ti
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
44/101
Handling Exceptions
When catching an exception of a particular class, all
its inheritors (child exceptions) are caught too
Example:
Handles ArithmeticExceptionand its successorsDivideByZeroExceptionand OverflowException
44
try{
// Do some works that can raise an exception}catch (System.ArithmeticException){
// Handle the caught arithmetic exception}
H dli All E ti
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
45/101
Handling All Exceptions
All exceptions thrown by .NET managed codeinherit the System.Exceptionexception
Unmanaged code can throw other exceptions
For handling all exceptions (even unmanaged)use the construction:
45
try{
// Do some works that can raise any exception
}catch{
// Handle the caught exception}
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
46/101
H E ti W k?
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
47/101
How Exceptions Work?
47
Main()
Method 1
Method 2
Method N
2. Method call
3. Method call
4. Method call
Main()
Method 1
Method 2
Method N
8. Find handler
7. Find handler
6. Find handler
5. Throw an exception
.NETCLR
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
48/101
Th i E ti E l
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
49/101
Throwing Exceptions Example
49
public static double Sqrt(double value){
if (value < 0)throw new System.ArgumentOutOfRangeException(
"Sqrt for negative numbers is undefined!");return Math.Sqrt(value);
}static void Main(){
try{
Sqrt(-1);}
catch (ArgumentOutOfRangeException ex){Console.Error.WriteLine("Error: " + ex.Message);throw;
}}
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
50/101
Strings and Text Processing
What Is String?
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
51/101
What Is String?
Strings are sequences of characters
Each character is a Unicode symbol
Represented by the stringdata type in C#
(System.String) Example:
51
string s = "Hello, C#";
H e l l o , C #s
The System StringClass
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
52/101
The System.StringClass
Strings are represented by System.Stringobjects in .NET Framework
String objects contain an immutable (read-only)sequence of characters
Strings use Unicode in to support multiplelanguages and alphabets
Strings are stored in the dynamic memory(managed heap)
System.Stringis reference type
52
The System String Class (2)
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
53/101
The System.StringClass (2)
String objects are like arrays of characters
(char[])
Have fixed length (String.Length)
Elements can be accessed directly by index
The index is in the range [0...Length-1]
53
string s = "Hello!";int len = s.Length; // len = 6char ch = s[1]; // ch = 'e'
0 1 2 3 4 5
H e l l o !
index =s[index] =
Strings Example
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
54/101
Strings Example
54
static void Main(){
string s =
"Stand up, stand up, Balkan Superman.";
Console.WriteLine("s = \"{0}\"", s);
Console.WriteLine("s.Length = {0}", s.Length);
for (int i = 0; i < s.Length; i++)
{
Console.WriteLine("s[{0}] = {1}", i, s[i]);
}}
Declaring Strings
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
55/101
Declaring Strings
There are two ways of declaring string
variables:
Using the C# keyword string
Using the .NET's fully qualified class nameSystem.String
The above three declarations are equivalent
55
string str1;
System.String str2;
String str3;
Creating Strings
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
56/101
Creating Strings
Before initializing a string variable has null
value
Strings can be initialized by:
Assigning a string literal to the string variable Assigning the value of another string variable
Assigning the result of operation of type string
56
Creating Strings (2)
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
57/101
Creating Strings (2)
Not initialized variables has value of null
Assigning a string literal
Assigning from another string variable
Assigning from the result of string operation
57
string s; // s is equal to null
string s = "I am a string literal!";
string s2 = s;
string s = 42.ToString();
Reading and Printing Strings
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
58/101
Reading and Printing Strings
Reading strings from the console Use the method Console.ReadLine()
58
string s = Console.ReadLine();
Console.Write("Please enter your name: ");string name = Console.ReadLine();
Console.Write("Hello, {0}! ", name);
Console.WriteLine("Welcome to our party!");
Printing strings to the console
Use the methods Write() and WriteLine()
Comparing Strings
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
59/101
Comparing Strings
A number of ways exist to compare two
strings:
Dictionary-based string comparison
Case-insensitive
Case-sensitive
59
int result = string.Compare(str1, str2, true);// result == 0 if str1 equals str2// result < 0 if str1 if before str2// result > 0 if str1 if after str2
string.Compare(str1, str2, false);
Comparing Strings Example
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
60/101
Comparing Strings Example
Finding the first string in a lexicographical order
from a given list of strings:
60
string[] towns = {"Sofia", "Varna", "Plovdiv","Pleven", "Bourgas", "Rousse", "Yambol"};
string firstTown = towns[0];for (int i=1; i
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
61/101
Concatenating Strings
There are two ways to combine strings:
Using the Concat()method
Using the +or the +=operators
Any object can be appended to string
61
string str = String.Concat(str1, str2);
string str = str1 + str2 + str3;string str += str1;
string name = "Peter";int age = 22;string s = name + " " + age; // "Peter 22"
Searching in Strings
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
62/101
Searching in Strings
Finding a character or substring within givenstring
First occurrence
First occurrence starting at given position
Last occurrence
62
IndexOf(string str)
IndexOf(string str, int startIndex)
LastIndexOf(string)
Searching in Strings Example
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
63/101
Searching in Strings Example
63
string str = "C# Programming Course";int index = str.IndexOf("C#"); // index = 0index = str.IndexOf("Course"); // index = 15index = str.IndexOf("COURSE"); // index = -1// IndexOf is case-sensetive. -1 means not foundindex = str.IndexOf("ram"); // index = 7index = str.IndexOf("r"); // index = 4index = str.IndexOf("r", 5); // index = 7index = str.IndexOf("r", 8); // index = 18
0 1 2 3 4 5 6 7 8 9 10 11 12 13
C # P r o g r a m m i n g
index =
s[index] =
Extracting Substrings
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
64/101
Extracting Substrings
Extracting substrings
str.Substring(int startIndex, int length)
str.Substring(int startIndex)
64
string filename = @"C:\Pics\Rila2009.jpg";string name = filename.Substring(8, 8);// name is Rila2009
string filename = @"C:\Pics\Summer2009.jpg";string nameAndExtension = filename.Substring(8);
// nameAndExtension is Summer2009.jpg
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
C : \ P i c s \ R i l a 2 0 0 5 . j p g
Splitting Strings
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
65/101
Splitting Strings
To split a string by given separator(s) use the
following method:
Example:
65
string[] Split(params char[])
string listOfBeers ="Amstel, Zagorka, Tuborg, Becks.";string[] beers =listOfBeers.Split(' ', ',', '.');
Console.WriteLine("Available beers are:");foreach (string beer in beers){
Console.WriteLine(beer);}
Replacing and Deleting Substrings
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
66/101
Replacing and Deleting Substrings
Replace(string,string)replaces all
occurrences of given string with another
The result is new string (strings are immutable)
Remove(index,length)deletes part of a string
and produces new string as result
66
string cocktail = "Vodka + Martini + Cherry";string replaced = cocktail.Replace("+", "and");
// Vodka and Martini and Cherry
string price = "$ 1234567";string lowPrice = price.Remove(2, 3);// $ 4567
Changing Character Casing
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
67/101
Changing Character Casing
Using method ToLower()
Using method ToUpper()
67
string alpha = "aBcDeFg";string lowerAlpha = alpha.ToLower(); // abcdefgConsole.WriteLine(lowerAlpha);
string alpha = "aBcDeFg";string upperAlpha = alpha.ToUpper(); // ABCDEFGConsole.WriteLine(upperAlpha);
Trimming White Space
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
68/101
Trimming White Space
Using method Trim()
Using method Trim(chars)
Using TrimStart()and TrimEnd()
68
string s = " example of white space ";string clean = s.Trim();Console.WriteLine(clean);
string s = " \t\nHello!!! \n";string clean = s.Trim(' ', ',' ,'!', '\n','\t');Console.WriteLine(clean); // Hello
string s = " C# ";string clean = s.TrimStart(); // clean = "C# "
Constructing Strings
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
69/101
Constructing Strings
Strings are immutable
Concat(), Replace(), Trim(), ... return newstring, do not modify the old one
Do not use "+" for strings in a loop!
It runs very, very inefficiently!
69
public static string DupChar(char ch, int count){
string result = "";for (int i=0; i
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
70/101
g g gStringBuilder
Use the System.Text.StringBuilderclass formodifiable strings of characters:
Use StringBuilderif you need to keep addingcharacters to a string
70
public static string ReverseString(string s){
StringBuilder sb = new StringBuilder();for (int i = s.Length-1; i >= 0; i--)
sb.Append(s[i]);return sb.ToString();
}
The StringBuilder Class
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
71/101
The StringBuilder Class
StringBuilderkeeps a buffer memory,
allocated in advance Most operations use the buffer memory and
do not allocate new objects
71
H e l l o , C # !StringBuilder:
Length=9
Capacity=15
Capacity
used buffer
(Length)
unusedbuffer
StringBuilder Example
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
72/101
StringBuilder Example
Extracting all capital letters from a string
72
public static string ExtractCapitals(string s){
StringBuilder result = new StringBuilder();for (int i = 0; i
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
73/101
Method ToString()
All classes have public virtual method
ToString()
Returns a human-readable, culture-sensitivestring representing the object
Most .NET Framework types have ownimplementation of ToString()
int, float, bool, DateTime
73
int number = 5;string s = "The number is " + number.ToString();Console.WriteLine(s); // The number is 5
Method ToString(format)
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
74/101
Method ToString(format)
We can apply specific formatting when
converting objects to string
ToString(formatString)method
74
int number = 42;string s = number.ToString("D5"); // 00042
s = number.ToString("X"); // 2A
// Consider the default culture is Bulgarians = number.ToString("C"); // 42,00
double d = 0.375;s = d.ToString("P2"); // 37,50 %
Formatting Strings
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
75/101
Formatting Strings
The formatting strings are different for the
different types
Some formatting strings for numbers:
Dnumber (for integer types)
Ccurrency (according to current culture)
Enumber in exponential notation
Ppercentage
Xhexadecimal number
Ffixed point (for real numbers)
75
Method String.Format()
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
76/101
Method String.Format()
Applies templatesfor formatting strings
Placeholders are used for dynamic text
Like Console.WriteLine()
76
string template = "If I were {0}, I would {1}.";string sentence1 = String.Format(template, "developer", "know C#");
Console.WriteLine(sentence1);// If I were developer, I would know C#.
string sentence2 = String.Format(template, "elephant", "weigh 4500 kg");
Console.WriteLine(sentence2);// If I were elephant, I would weigh 4500 kg.
Composite Formatting
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
77/101
Composite Formatting
The placeholders in the composite formatting
strings are specified as follows:
Examples:
77
{index[,alignment][:formatString]}
double d = 0.375;s = String.Format("{0,10:F5}", d);// s = " 0,37500"
int number = 42;Console.WriteLine("Dec {0:D} = Hex {1:X}",
number, number);// Dec 42 = Hex 2A
Formatting Dates
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
78/101
Formatting Dates
Dates have their own formatting strings
d, ddday (with/without leading zero)
M, MMmonth
yy, yyyyyear (2 or 4 digits) h, HH, m, mm, s, sshour, minute, second
78
DateTime now = DateTime.Now;
Console.WriteLine("Now is {0:d.MM.yyyy HH:mm:ss}", now);
// Now is 31.11.2009 11:30:32
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
79/101
Collection Classes
Lists, Trees, Dictionaries
What are Generics?
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
80/101
Generics allow defining parameterized classes
that process data of unknown (generic) type The class can be instantiated with several
different particular types
Example: List List/List/ List
Generics are also known as "parameterized
types" or "template types"
Similar to the templates in C++
Similar to the generics in Java80
The ListClass
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
81/101
Implements the abstract data structure list
using an array
All elements are of the same type T
Tcan be any type, e.g. List,List, List
Size is dynamically increased as needed
Basic functionality: Countreturns the number of elements
Add(T)appends given element at the end
81
ListSimple Example
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
82/101
p p
82
static void Main()
{ List list = new List();
list.Add("C#");list.Add("Java");list.Add("PHP");
foreach (string item in list){
Console.WriteLine(item);}
// Result:// C#// Java// PHP
}
ListFunctionality
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
83/101
y
list[index]access element by index
Insert(index,T)inserts given element to thelist at a specified position
Remove(T)removes the first occurrence of
given element
RemoveAt(index)removes the element at thespecified position
Clear()removes all elements
Contains(T)determines whether an elementis part of the list
83
ListFunctionality (2)
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
84/101
y ( )
IndexOf()returns the index of the first
occurrence of a value in the list (zero-based)
Reverse()reverses the order of the elements inthe list or a portion of it
Sort()sorts the elements in the list or aportion of it
ToArray()converts the elements of the list to
an array
TrimExcess()sets the capacity to the actualnumber of elements
84
Primes in an Interval Example
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
85/101
p
85
static List FindPrimes(int start, int end){
List primesList = new List();
for (int num = start; num
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
86/101
Implements the stackdata structure using an
array
Elements are of the same type T
Tcan be any type, e.g. Stack
Size is dynamically increased as needed
Basic functionality:
Push(T)inserts elements to the stack Pop()removes and returns the top element
from the stack
86
StackExample
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
87/101
p
Using Push(), Pop()and Peek()methods
87
static void Main(){
Stack stack = new Stack();
stack.Push("1. Ivan");
stack.Push("2. Nikolay");stack.Push("3. Maria");stack.Push("4. George");
Console.WriteLine("Top = {0}", stack.Peek());
while (stack.Count > 0)
{ string personName = stack.Pop();Console.WriteLine(personName);
}}
The QueueClass
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
88/101
Q
Implements the queue data structure using a
circular resizable array Elements are from the same type T
Tcan be any type, e.g. Stack
Size is dynamically increased as needed
Basic functionality:
Enqueue(T)adds an element to theend of the queue
Dequeue()removes and returns theelement at the beginning of the queue
88
QueueExample
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
89/101
Q p
Using Enqueue()and Dequeue()methods
89
static void Main(){
Queue queue = new Queue();
queue.Enqueue("Message One");
queue.Enqueue("Message Two");queue.Enqueue("Message Three");queue.Enqueue("Message Four");
while (queue.Count > 0){
string message = queue.Dequeue();Console.WriteLine(message);
}}
DictionaryClass
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
90/101
y y
Implements the abstract data type
"Dictionary" as hash table
Size is dynamically increased as needed
Contains a collection of key-and-valuepairs arranged by the hash code of thekey h(key) = value
Collisions are resolved by chaining
Dictionaryclass relies on
Object.Equals()method forcomparing elements
90
DictionaryClass(2)
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
91/101
(2) Object.GetHashCode()method for
calculating the hash codes of the elements Major operations:
Add(TKey,TValue)adds an element
with the specified key and value into thedictionary
Remove(TKey)removes the element with
the specified key Clear()removes all elements
this[]returns element by key91
DictionaryClass(3)
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
92/101
(3) Countreturns the number of elements
ContainsKey(TKey)determines whetherthe dictionary contains given key
ContainsValue(TValue)determines
whether the dictionary contains given value
Keysreturns a collection of the keys
Valuesreturns a collection of the values
TryGetValue(TKey,out TValue)if the keyis found, returns it in the TValue, otherwisereturns the default value for the TValuetype
92
DictionaryExample
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
93/101
Example
93
Dictionary studentsMarks= new Dictionary();
studentsMarks.Add("Ivan", 4);studentsMarks.Add("Peter", 6);studentsMarks.Add("Maria", 6);studentsMarks.Add("George", 5);int peterMark = studentsMarks["Peter"];
Console.WriteLine("Peter's mark: {0}", peterMark);Console.WriteLine("Is Peter in the hash table: {0}",
studentsMarks.ContainsKey("Peter"));Console.WriteLine("Students and grades:");
foreach (var pair in studentsMarks){Console.WriteLine("{0} --> {1} ", pair.Key,
pair.Value);}
Counting Words in Given Text
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
94/101
94
string text = "Welcome to our C# course. In this " +"course you will learn how to write simple " +
"programs in C# and Microsoft .NET";string[] words = text.Split(new char[] {' ', ',', '.'},StringSplitOptions.RemoveEmptyEntries);var wordsCount = new Dictionary();
foreach (string word in words)
{if (wordsCount.ContainsKey(word))wordsCount[word]++;elsewordsCount.Add(word, 1);
}
foreach (var pair in wordsCount){Console.WriteLine("{0} --> {1}", pair.Key, pair.Value);
}
Balanced Trees in .NET
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
95/101
Balanced Binary Search Trees
Ordered binary search trees that have height oflog2(n)where nis the number of their nodes
Searching costs about log2(n)comparisons
.NET Framework has built-in implementationsof balanced search trees, e.g.:
SortedDictionary
Red-black tree based map of key-value pairs
External libraries like "Wintellect PowerCollections for .NET" are more flexible
95
Sorted Dictionary Example
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
96/101
96
string text = "Welcome to our C# course. In this " +"course you will learn how to write simple " +
"programs in C# and Microsoft .NET";string[] words = text.Split(new char[] {' ', ',', '.'},StringSplitOptions.RemoveEmptyEntries);var wordsCount = new SortedDictionary();
foreach (string word in words){
if (wordsCount.ContainsKey(word))wordsCount[word]++;elsewordsCount.Add(word, 1);
}
foreach (var pair in wordsCount){Console.WriteLine("{0} --> {1}", pair.Key, pair.Value);
}
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
97/101
AttributesWhat They Are? How and When to Use Them?
What Are Attributes?
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
98/101
Special declarative tags for attaching
descriptive information (annotations) to thedeclarations in the code
At compile time attributes are saved in the
assembly's metadata
Can be extracted from the metadata and canbe manipulated by different tools
Instances of classes derived fromSystem.Attribute
98
Attributes Applying Example
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
99/101
Attribute's name is surrounded by square
brackets and is placed before the declarationwhich it refers to:
[Flags]attribute indicates that the enumtype can be treated like a set of bit flags
99
[Flags] // System.FlagsAttribute
public enum FileAccess{Read = 1,Write = 2,ReadWrite = Read | Write
}
Attributes With Parameters
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
100/101
Attributes use parameters for initialization:
In the example the [DllImport]attribute isinstantiated by the compiler as follows:
An object of System.Runtime.InteropServices.DllImportAttributeclass is created and initialized
100
[DllImport("user32.dll", EntryPoint="MessageBox")]public static extern int ShowMessageBox(int hWnd,string text, string caption, int type);...ShowMessageBox(0, "Some text", "Some caption", 0);
C# Language Overview(Part II)
8/13/2019 4 Csharp Language Overview Part II 120201085223 Phpapp02
101/101
(Part II)
Questions?