Creating and Using Objects, Exceptions, Strings, Generics, Collections, Attributes Doncho Minkov
Technical Trainer
http://www.minkov.it
Telerik School Academy
schoolacademy.telerik.com
Table of Contents
1. 2. 3. 4. 5. 6.
Creating and Using Objects Exceptions Handling Strings and Text Processing Generics Collection Classes Attributes
What is Class?
The formal definition of
class:
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.
Definition by Google
Classes
Classes
define:
Set of attributes
Represented by fields and properties Hold their state
Classes Example
Class Name
Account +Owner: Person +Ammount: double
+Suspend() +Deposit(sum:double) +Withdraw(sum:double)
Operations (Methods)
Objects
An object is a concrete instance of a particular
class
Creating
Example:
Objects Example
Class
Account +Owner: Person +Ammount: double +Suspend() +Deposit(sum:double) +Withdraw(sum:double) ivanAccount
Object
Object
Object
Classes in C#
Basic
Properties
Methods
Constructors
Inner types Etc. (events, indexers, operators, )
9
Classes in C# Examples
Example of classes:
System.Array
System.Math
System.Random
10
Declaring Objects
An instance of a class
not initialized
// Declare and initialize a structure instance DateTime today = DateTime.Now;
11
Fields
Fields are data members of a class Can be variables
and constants of
the object
Example:
12
Accessing Fields
Constant fields can be only read Variable
Usually properties
Examples:
13
Properties
Properties
look like fields (have name and type), but they can contain code, executed when they are accessed fields (wrappers), but can contain more complex logic
Properties (2)
According to the implemented accessors
String.Length
15
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));
16
of a class
Example: DateTime.MinValue is shared between all instances of DateTime
17
Methods
Methods manipulate the data of the object to
Console.WriteLine()
Console.ReadLine()
String.Substring(index, length) Array.GetLength(index)
19
Instance Methods
Instance methods manipulate the data of a
The name of the instance, followed by the name of the method, separated by dot
<object_name>.<method_name>(<parameters>)
20
String sampleLower = new String('a', 5); String sampleUpper = sampleLower.ToUpper(); Console.WriteLine(sampleLower); // aaaaa Console.WriteLine(sampleUpper); // AAAAA
Calling
Static Methods
Static methods are common for all instances of
The name of the class, followed by the name of the method, separated by dot
<class_name>.<method_name>(<parameters>)
22
Constant field
Static method
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); Static Console.WriteLine( method "{0}; {1}; {2}", precise, round3, round1); // 8,7654321; 8,765; 8,8
Static method
23
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
Constructors (2)
Constructor
Examples:
String s = new String("Hello!"); // s = "Hello!" String s = new String('*', 5); // s = "*****" DateTime dt = new DateTime(2009, 12, 30); DateTime dt = new DateTime(2009, 12, 30, 12, 33, 59);
Structures
Structures are similar Structures are usually
to classes
Structures are
value types, and classes are reference types (this will be discussed later)
System.DateTime represents a date and time
26
Example of structure
What is a Namespace?
Namespaces are used to organize the source
Definitions of classes, structures, interfaces and other types and other namespaces
Namespaces can contain other namespaces For example:
Example:
28
Including Namespaces
The using directive in C#:
using <namespace_name>
Allows
Example:
instead of
System.DateTime date;
29
Framework
Primitive types (e.g. int, float, object) Classes (e.g. String, Console, Array)
Etc.
Object-oriented by design
30
CTS Type
System.Int32
C# Type
int
VB.NET Type
Integer
System.Single System.Boolean
System.String System.Object
float bool
string object
Single Boolean
String Object
31
Most of the primitive types Structures Examples: int, float, bool, DateTime
Reference types
Strings
Arrays Examples: string, Random, object, int[]
33
Exceptions Handling
The Paradigm of Exceptions in OOP
Handling Exceptions
In C# the exceptions can be handled by the
try-catch-finally construction
try { // Do some work that can raise an exception } catch (SomeException) { // Handle the caught exception }
exceptions in CLR
Contains 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)
38
Exception Properties
The StackTrace property is extremely useful when identifying the reason caused the exception
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:\consoleapplication1\exceptionstest.cs:line 8 at ExceptionsTest.Main(String[] args) in c:\consoleapplication1\exceptionstest.cs:line 15
40
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:
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)
41
Exception Hierarchy
Exceptions in .NET Framework are organized
in a hierarchy
42
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
Handling Exceptions
When catching an exception of a particular class, all its inheritors (child exceptions) are caught too
Example:
try { // Do some works that can raise an exception
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:
try { // Do some works that can raise any exception } catch { // Handle the caught exception }
45
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 exception travels over the stack until a suitable catch block is reached to handle it
Unhandled exceptions display
error message
46
Method N Method 2
4. Method call
Method N Method 2
6. Find handler
3. Method call
7. Find handler
Method 1
2. Method call
Method 1
8. Find handler
Main()
47
What Is String?
Strings
(System.String)
Example:
string s = "Hello, C#";
51
index = 0 1 2 3 4 5 s[index] = H e l l o !
53
Strings Example
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]); } }
54
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
string str1; System.String str2; String str3;
Creating Strings
Before initializing
value
Strings
56
57
Printing
Comparing Strings
A number of ways
strings:
Dictionary-based string comparison
Case-insensitive
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
Case-sensitive
string.Compare(str1, str2, false);
59
Finding the first string in a lexicographical order from a given list of strings:
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);
60
Concatenating Strings
61
Searching in Strings
Last occurrence
LastIndexOf(string)
62
index = 0 1 s[index] = C #
10
11
12
13
P r o g r a m m i n g
63
Extracting Substrings
Extracting substrings
str.Substring(int startIndex)
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
64
Splitting Strings
Example:
string listOfBeers = "Amstel, Zagorka, Tuborg, Becks."; string[] beers = listOfBeers.Split(' ', ',', '.'); Console.WriteLine("Available beers are:"); foreach (string beer in beers) { Console.WriteLine(beer); }
65
Remove(index, length) deletes part of a string and produces new string as result
string price = "$ 1234567"; string lowPrice = price.Remove(2, 3); // $ 4567
66
67
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!
unused buffer
allocated in advance
Most operations use the buffer memory and do not allocate new objects
71
StringBuilder Example
Extracting all capital
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(); }
72
Method ToString()
All classes
Method ToString(format)
We can apply
Formatting Strings
X hexadecimal number
F fixed point (for real numbers)
75
Method String.Format()
Applies templates for formatting strings
Composite Formatting
Examples:
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
77
Formatting Dates
Dates have their
78
Collection Classes
Lists, Trees, Dictionaries
using an 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
81
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
IndexOf() returns the index of the first occurrence of a value in the list (zero-based)
array
Elements are of the same type T T can be any type, e.g. Stack<int>
functionality:
Push(T) inserts elements to the stack Pop() removes and returns the top element from the stack
86
Stack<T> Example
functionality:
Enqueue(T) adds an element to the end of the queue Dequeue() removes and returns the element at the beginning of the queue
88
Queue<T> Example
Dictionary<TKey,TValue> Class
Implements the abstract
Dictionary<TKey,TValue> class
relies on
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
91
TryGetValue(TKey,out TValue) if the key is found, returns it in the TValue, otherwise returns the default value for the TValue type
92
Dictionary<TKey,Tvalue> Example
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); }
93
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
Attributes
What They Are? How and When to Use Them?
tags for attaching descriptive information (annotations) to the declarations in the code are saved in the assembly's metadata
name is surrounded by square brackets and is placed before the declaration which it refers to:
[Flags] // System.FlagsAttribute public enum FileAccess { Read = 1, Write = 2, ReadWrite = Read | Write }
[Flags] attribute
indicates that the enum type can be treated like a set of bit flags
99
Questions?
http://academy.telerik.com