4. What is Class?
īŽ The formal definition of class:
Definition by Google
4
Classes act as templates from which an
instance of an object is created at run
time. Classes define the properties of the
object and the methods used to control
the object's behavior.
5. 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
6. Classes â Example
6
Account
+Owner: Person
+Ammount: double
+Suspend()
+Deposit(sum:double)
+Withdraw(sum:double)
Class Name Attributes
(Properties
and Fields)
Operations
(Methods)
7. Objects
īŽ An object is a concrete instance of a particular
class
īŽ Creating an object from a class is called
instantiation
īŽ Objects have state
ī Set of values associated to their attributes
īŽ Example:
ī Class: Account
ī Objects: Ivan's account, Peter's account
7
8. 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
9. 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
10. Classes in C# â Examples
īŽ Example of classes:
ī System.Console
ī System.String (string in C#)
ī System.Int32 (int in C#)
ī System.Array
ī System.Math
ī System.Random
10
11. Declaring Objects
īŽ An instance of a class or structure can be
defined like any other variable:
īŽ Instances cannot be used if they are
not initialized
11
using System;
...
// Define two variables of type DateTime
DateTime today;
DateTime halloween;
// Declare and initialize a structure instance
DateTime today = DateTime.Now;
12. Fields
īŽ Fields are data members of a class
īŽ Can be variables and constants
īŽ Accessing a field doesnât invoke any actions of
the object
īŽ Example:
ī String.Empty (the "" string)
12
13. 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 field
int maxInt = Int32.MaxValue;
14. Properties
īŽ Properties look like fields (have name and
type), but they can contain code, executed
when they are accessed
īŽ Usually used to control access to data
fields (wrappers), but can contain more
complex logic
īŽ Can have two components (and at least one
of them) called accessors
ī get for reading their value
ī set for changing their value
14
15. Properties (2)
īŽ According to the implemented accessors
properties can be:
ī Read-only (get accessor only)
ī Read and write (both get and set accessors)
ī Write-only (set accessor only)
īŽ Example of read-only property:
ī String.Length
15
16. 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));
17. Instance and Static Members
īŽ Fields, properties and methods can be:
ī Instance (or object members)
ī Static (or class members)
īŽ Instance members are specific for each object
ī Example: different dogs have different name
īŽ Static members are common for all instances
of a class
ī Example: DateTime.MinValue is shared
between all instances of DateTime
17
18. Instance and Static
Members â 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 to
create an instance of it
18
19. Methods
īŽ Methods manipulate the data of the object to
which they belong or perform other tasks
īŽ Examples:
ī Console.WriteLine(âĻ)
ī Console.ReadLine()
ī String.Substring(index, length)
ī Array.GetLength(index)
19
20. Instance Methods
īŽ Instance methods manipulate the data of a
specified object or perform any other tasks
ī If a value is returned, it depends on the
particular class instance
īŽ Syntax:
ī The name of the instance, followed by the
name of the method, separated by dot
20
<object_name>.<method_name>(<parameters>)
22. Static Methods
īŽ Static methods are common for all instances of
a class (shared between all instances)
ī Returned value depends only on the passed
parameters
ī No particular class instance is available
īŽ Syntax:
ī The name of the class, followed by the name of
the method, separated by dot
22
<class_name>.<method_name>(<parameters>)
24. Constructors
īŽ Constructors are special methods used to
assign initial values of the fields in an object
ī Executed when an object of a given type is
being created
ī Have the same name as the class that holds
them
ī Do not return a value
īŽ A class may have several constructors with
different set of parameters
24
25. Constructors (2)
īŽ Constructor is invoked by the new operator
īŽ Examples:
25
String s = new String("Hello!"); // s = "Hello!"
<instance_name> = new <class_name>(<parameters>)
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);
26. Structures
īŽ Structures are similar to classes
īŽ Structures are usually used for storing data
structures, 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.DateTime â represents a date and time
26
27. Enumerations
īŽ Enumerations in C# are types whose values are
limited to a predefined set of values
ī E.g. the days of week
ī Declared by the keyword enum in C#
ī Hold values from a predefined set
27
public enum Color { Red, Green, Blue, Black }
âĻ
Color color = Color.Red;
Console.WriteLine(color); // Red
color = 5; // Compilation error!
28. 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 and
other types and other namespaces
īŽ Namespaces can contain other namespaces,
e.g.
ī System namespace contains Data namespace
ī The name of the nested namespace is
System.Data
28
29. Full Class Names
īŽ A full name of a class is the name of the class
preceded by the name of its namespace
īŽ Example:
ī Array class, defined in the System namespace
ī The full name of the class is System.Array
29
<namespace_name>.<class_name>
30. Including Namespaces
īŽ The using directive in C#:
īŽ Allows using types in a namespace, without
specifying their full name
īŽ Example:
instead of
30
using <namespace_name>
using System;
DateTime date;
System.DateTime date;
31. CommonType System (CTS)
īŽ CTS defines all data types supported in .NET
Framework
ī 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
31
32. CTS and Different Languages
īŽ CTS is common for all .NET languages
ī C#,VB.NET, J#, JScript.NET, ...
īŽ CTS type mappings:
32
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
33. Value and ReferenceTypes
īŽ In CTS there are two categories of types
ī Value types
ī 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
33
34. 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[]
34
36. What are Exceptions?
īŽ The exceptions in .NET Framework are classic
implementation of the OOP exception model
īŽ Deliver powerful mechanism for centralized
handling 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
36
37. Handling Exceptions
īŽ In C# the exceptions can be handled by the
try-catch-finally construction
īŽ catch blocks can be used multiple times to
process different exception types
37
try
{
// Do some work that can raise an exception
}
catch (SomeException)
{
// Handle the caught exception
}
38. Handling Exceptions â Example
38
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!");
}
}
39. The System.Exception Class
īŽ Exceptions in .NET are objects
īŽ The System.Exception class is base for all
exceptions in CLR
ī Holds information for the cause of the error or
the unusual situation
ī Message â text description of the exception
ī StackTrace â the snapshot of the stack at the
moment of exception throwing
ī InnerException â exception caused the current
exception (if any)
39
41. Exception Properties
īŽ The Message property gives brief description of the
problem
īŽ The StackTrace property is extremely useful when
identifying the reason caused the exception
41
Exception caught: Input string was not in a correct
format.
at System.Number.ParseInt32(String s, NumberStyles
style, NumberFormatInfo info)
at System.Int32.Parse(String s)
at ExceptionsTest.CauseFormatException() in
c:consoleapplication1exceptionstest.cs:line 8
at ExceptionsTest.Main(String[] args) in
c:consoleapplication1exceptionstest.cs:line 15
42. Exception Properties (2)
īŽ File names and line numbers are accessible only if the
compilation was in Debug mode
īŽ When compiled in Release mode, the information in
the property StackTrace is quite different:
42
Exception caught: Input string was not in a correct
format.
at System.Number.ParseInt32(String s, NumberStyles
style, NumberFormatInfo info)
at ExceptionsTest.Main(String[] args)
44. 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 from
System.ApplicationException
44
45. Handling Exceptions
īŽ When catching an exception of a particular class, all
its inheritors (child exceptions) are caught too
īŽ Example:
īŽ Handles ArithmeticException and its successors
DivideByZeroException and OverflowException
45
try
{
// Do some works that can raise an exception
}
catch (System.ArithmeticException)
{
// Handle the caught arithmetic exception
}
46. Handling All Exceptions
īŽ All exceptions thrown by .NET managed code
inherit the System.Exception exception
īŽ Unmanaged code can throw other exceptions
īŽ For handling all exceptions (even unmanaged)
use the construction:
46
try
{
// Do some works that can raise any exception
}
catch
{
// Handle the caught exception
}
47. Throwing Exceptions
īŽ Exceptions are thrown (raised) by throw
keyword in C#
ī Used to notify the calling code in case of error
or unusual situation
īŽ When an exception is thrown:
ī The program execution stops
ī The exception travels over the stack until a
suitable catch block is reached to handle it
īŽ Unhandled exceptions display error message
47
49. Using throw Keyword
īŽ Throwing an exception with error message:
īŽ Exceptions can take message and cause:
īŽ Note: if the original exception is not passed the
initial cause of the exception is lost
49
throw new ArgumentException("Invalid amount!");
try
{
Int32.Parse(str);
}
catch (FormatException fe)
{
throw new ArgumentException("Invalid number", fe);
}
50. Throwing Exceptions â Example
50
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;
}
}
52. What Is String?
īŽ Strings are sequences of characters
īŽ Each character is a Unicode symbol
īŽ Represented by the string data type in C#
(System.String)
īŽ Example:
52
string s = "Hello, C#";
H e l l o , C #s
53. The System.String Class
īŽ Strings are represented by System.String
objects in .NET Framework
ī String objects contain an immutable (read-only)
sequence of characters
ī Strings use Unicode in to support multiple
languages and alphabets
īŽ Strings are stored in the dynamic memory
(managed heap)
īŽ System.String is reference type
53
54. The System.String Class (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]
54
string s = "Hello!";
int len = s.Length; // len = 6
char ch = s[1]; // ch = 'e'
0 1 2 3 4 5
H e l l o !
index =
s[index] =
55. Strings â Example
55
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]);
}
}
56. Declaring Strings
īŽ There are two ways of declaring string
variables:
ī Using the C# keyword string
ī Using the .NET's fully qualified class name
System.String
ī The above three declarations are equivalent
56
string str1;
System.String str2;
String str3;
57. 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
57
58. 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
58
string s; // s is equal to null
string s = "I am a string literal!";
string s2 = s;
string s = 42.ToString();
59. Reading and Printing Strings
īŽ Reading strings from the console
ī Use the method Console.ReadLine()
59
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 methodsWrite() and WriteLine()
60. Comparing Strings
īŽ A number of ways exist to compare two
strings:
ī Dictionary-based string comparison
ī Case-insensitive
ī Case-sensitive
60
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);
61. Comparing Strings â Example
īŽ Finding the first string in a lexicographical order
from a given list of strings:
61
string[] towns = {"Sofia", "Varna", "Plovdiv",
"Pleven", "Bourgas", "Rousse", "Yambol"};
string firstTown = towns[0];
for (int i=1; i<towns.Length; i++)
{
string currentTown = towns[i];
if (String.Compare(currentTown, firstTown) < 0)
{
firstTown = currentTown;
}
}
Console.WriteLine("First town: {0}", firstTown);
62. Concatenating Strings
īŽ There are two ways to combine strings:
ī Using the Concat() method
ī Using the + or the += operators
īŽ Any object can be appended to a string
62
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"
63. Searching in Strings
īŽ Finding a character or substring within given
string
ī First occurrence
ī First occurrence starting at given position
ī Last occurrence
63
IndexOf(string str)
IndexOf(string str, int startIndex)
LastIndexOf(string)
64. Searching in Strings â Example
64
string str = "C# Programming Course";
int index = str.IndexOf("C#"); // index = 0
index = str.IndexOf("Course"); // index = 15
index = str.IndexOf("COURSE"); // index = -1
// IndexOf is case-sensetive. -1 means not found
index = str.IndexOf("ram"); // index = 7
index = str.IndexOf("r"); // index = 4
index = str.IndexOf("r", 5); // index = 7
index = 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] =
65. Extracting Substrings
īŽ Extracting substrings
ī str.Substring(int startIndex, int length)
ī str.Substring(int startIndex)
65
string filename = @"C:PicsRila2009.jpg";
string name = filename.Substring(8, 8);
// name is Rila2009
string filename = @"C:PicsSummer2009.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
66. Splitting Strings
īŽ To split a string by given separator(s) use the
following method:
īŽ Example:
66
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);
}
67. 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 a new string as result
67
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
69. Trimming White Space
īŽ Using method Trim()
īŽ Using method Trim(chars)
īŽ Using TrimStart() and TrimEnd()
69
string s = " example of white space ";
string clean = s.Trim();
Console.WriteLine(clean);
string s = " tnHello!!! n";
string clean = s.Trim(' ', ',' ,'!', 'n','t');
Console.WriteLine(clean); // Hello
string s = " C# ";
string clean = s.TrimStart(); // clean = "C# "
70. Constructing Strings
īŽ Strings are immutable
ī Concat(), Replace(), Trim(), ... return new
string, do not modify the old one
īŽ Do not use "+" for strings in a loop!
ī It runs very, very inefficiently (slowly)!
70
public static string DupChar(char ch, int count)
{
string result = "";
for (int i=0; i<count; i++)
result += ch;
return result;
}
Very bad practice.
Avoid this!
71. Changing the Contents of a
String â StringBuilder
īŽ Use the System.Text.StringBuilder class for
modifiable strings of characters:
īŽ Use StringBuilder if you need to keep adding
characters to a string
71
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();
}
72. The StringBuilder Class
īŽ StringBuilder keeps a buffer memory,
allocated in advance
ī Most operations use the buffer memory and
do not allocate new objects
72
H e l l o , C # !StringBuilder:
Length=9
Capacity=15
Capacity
used buffer
(Length)
unused
buffer
73. StringBuilder â Example
īŽ Extracting all capital letters from a string
73
public static string ExtractCapitals(string s)
{
StringBuilder result = new StringBuilder();
for (int i = 0; i<s.Length; i++)
{
if (Char.IsUpper(s[i]))
{
result.Append(s[i]);
}
}
return result.ToString();
}
74. Method ToString()
īŽ All classes have public virtual method
ToString()
ī Returns a human-readable, culture-sensitive
string representing the object
ī Most .NET Framework types have own
implementation of ToString()
ī int, float, bool, DateTime
74
int number = 5;
string s = "The number is " + number.ToString();
Console.WriteLine(s); // The number is 5
75. Method ToString(format)
īŽ We can apply specific formatting when
converting objects to string
ī ToString(formatString) method
75
int number = 42;
string s = number.ToString("D5"); // 00042
s = number.ToString("X"); // 2A
// Consider the default culture is Bulgarian
s = number.ToString("C"); // 42,00 Đģв
double d = 0.375;
s = d.ToString("P2"); // 37,50 %
76. Formatting Strings
īŽ The formatting strings are different for the
different types
īŽ Some formatting strings for numbers:
ī D â number (for integer types)
ī C â currency (according to current culture)
ī E â number in exponential notation
ī P â percentage
ī X â hexadecimal number
ī F â fixed point (for real numbers)
76
77. Method String.Format()
īŽ Applies templates for formatting strings
ī Placeholders are used for dynamic text
ī Like Console.WriteLine(âĻ)
77
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.
78. Composite Formatting
īŽ The placeholders in the composite formatting
strings are specified as follows:
īŽ Examples:
78
{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
79. Formatting Dates
īŽ Dates use their own formatting strings
ī d, dd â day (with/without leading zero)
ī M, MM â month
ī yy, yyyy â year (2 or 4 digits)
ī h, hh, m, mm, s, ss â hour, minute, second
79
DateTime now = DateTime.Now;
Console.WriteLine(
"Now is {0:d.MM.yyyy hh:mm:ss}", now);
// Now is 31.11.2009 11:30:32
81. What are Generics?
īŽ Generics allow defining parameterized classes
that process data of unknown (generic) type
ī The class can be instantiated with several
different particular types
ī Example: List<T> ī List<int> /
List<string> / List<Student>
īŽ Generics are also known as "parameterized
types" or "template types"
ī Similar to the templates in C++
ī Similar to the generics in Java
81
82. The List<T> Class
īŽ Implements the abstract data structure list
using an auto-extensible array
ī All elements are of the same type T
ī T can be any type, e.g. List<int>,
List<string>, List<DateTime>
ī Size is dynamically increased as needed
īŽ Basic functionality:
ī Count â returns the number of elements
ī Add(T) â appends given element at the end
82
83. List<T> â Simple Example
83
static void Main()
{
List<string> list = new List<string>();
list.Add("C#");
list.Add("Java");
list.Add("PHP");
foreach (string item in list)
{
Console.WriteLine(item);
}
// Result:
// C#
// Java
// PHP
}
84. List<T> â Functionality
īŽ list[index] â access element by index
īŽ Insert(index, T) â inserts given element to the
list at a specified position
īŽ Remove(T) â removes the first occurrence of
given element
īŽ RemoveAt(index) â removes the element at the
specified position
īŽ Clear() â removes all elements
īŽ Contains(T) â determines whether an element
is part of the list
84
85. List<T> â Functionality (2)
īŽ IndexOf() â returns the index of the first
occurrence of a value in the list (zero-based)
īŽ Reverse() â reverses the order of the elements in
the list or a portion of it
īŽ Sort() â sorts the elements in the list or a
portion of it
īŽ ToArray() â converts the elements of the list to
an array
īŽ TrimExcess() â sets the capacity to the actual
number of elements
85
86. Primes in an Interval â Example
86
static List<int> FindPrimes(int start, int end)
{
List<int> primesList = new List<int>();
for (int num = start; num <= end; num++)
{
bool prime = true;
for (int div = 2; div <= Math.Sqrt(num); div++)
{
if (num % div == 0)
{
prime = false;
break;
}
}
if (prime)
{
primesList.Add(num);
}
}
return primesList;
}
87. The Stack<T> Class
īŽ Implements the stack data structure using an
array
ī Elements are of the same type T
ī T can be any type, e.g. Stack<int>
ī 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
87
88. Stack<T> â Example
īŽ Using Push(), Pop() and Peek() methods
88
static void Main()
{
Stack<string> stack = new Stack<string>();
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);
}
}
89. The Queue<T> Class
īŽ Implements the queue data structure using a
circular resizable array
ī Elements are from the same type T
ī T can be any type, e.g. Stack<int>
ī Size is dynamically increased as needed
īŽ Basic functionality:
ī Enqueue(T) â adds an element to the end of
the queue
ī Dequeue() â removes and returns the
element at the beginning of the queue
89
90. Queue<T> â Example
īŽ Using Enqueue() and Dequeue() methods
90
static void Main()
{
Queue<string> queue = new Queue<string>();
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);
}
}
91. Dictionary<TKey,TValue> Class
īŽ Implements the abstract data type
"Dictionary" as hash table
ī Size is dynamically increased as needed
ī Contains a collection of key-value pairs
arranged by the hash code of the key:
ī h(key) = value
ī Collisions are resolved by chaining
īŽ Dictionary<TKey,TValue> class relies on
ī Object.Equals() method for comparing the
elements
91
92. Dictionary<TKey,TValue>
Class (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 the
dictionary
ī Remove(TKey) â removes the element with
the specified key
ī Clear() â removes all elements
ī this[] â returns element by key
92
93. Dictionary<TKey,TValue>
Class (3)
ī Count â returns the number of elements
ī ContainsKey(TKey) â determines whether
the dictionary contains given key
ī ContainsValue(TValue) â determines
whether the dictionary contains given value
ī Keys â returns a collection of the keys
ī Values â returns a collection of the values
ī TryGetValue(TKey,out TValue) â if the key
is found, returns it in the TValue, otherwise
returns the default value for the TValue type
93
94. Dictionary<TKey,TValue> â
Example
94
Dictionary<string, int> studentsMarks =
new Dictionary<string, int>();
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);
}
95. Counting Words in GivenText
95
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<string, int>();
foreach (string word in words)
{
if (wordsCount.ContainsKey(word))
wordsCount[word]++;
else
wordsCount.Add(word, 1);
}
foreach (var pair in wordsCount)
{
Console.WriteLine("{0} --> {1}", pair.Key, pair.Value);
}
96. BalancedTrees in .NET
īŽ Balanced Binary SearchTrees
ī Ordered binary search trees that have height of
log2(n) where n is the number of their nodes
ī Searching costs about log2(n) comparisons
īŽ .NET Framework has built-in implementations
of balanced search trees, e.g.:
ī SortedDictionary<K,V>
ī Red-black tree based map of key-value pairs
īŽ External libraries like "Wintellect Power
Collections for .NET" are more flexible
96
97. Sorted Dictionary â Example
97
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<string, int>();
foreach (string word in words)
{
if (wordsCount.ContainsKey(word))
wordsCount[word]++;
else
wordsCount.Add(word, 1);
}
foreach (var pair in wordsCount)
{
Console.WriteLine("{0} --> {1}", pair.Key, pair.Value);
}
99. What Are Attributes?
īŽ Attributes are special declarative tags
ī Used for attaching descriptive information
(annotations) to the declarations in the code
īŽ At compile time attributes are saved in the
assembly's metadata
ī Can be extracted from the metadata at run-
time and can be manipulated by different tools
īŽ Instances of classes derived from
System.Attribute
99
100. Attributes Applying â Example
īŽ Attribute's name is surrounded by square
brackets and is placed before the declaration
which it refers to:
īŽ [Flags] attribute indicates that the enum
type can be treated like a set of bit flags
100
[Flags] // System.FlagsAttribute
public enum FileAccess
{
Read = 1,
Write = 2,
ReadWrite = Read | Write
}
101. Attributes With Parameters
īŽ Attributes use parameters for initialization:
īŽ In this example the [DllImport] attribute is
instantiated by the compiler
ī A System.Runtime.InteropServices.
DllImportAttribute object is created,
initialized and put into the assembly metadata
101
[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) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*