SlideShare a Scribd company logo
C# Language Overview (Part II) Creating and Using Objects, Exceptions, Strings, Generics, Collections, Attributes Doncho Minkov Telerik School Academy schoolacademy.telerik.com   Technical Trainer http://www.minkov.it
Table of Contents Creating and Using Objects Exceptions Handling Strings and Text Processing Generics Collection Classes Attributes
Using Classes and Objects Using the Standard .NET Framework Classes
What is Class? The formal definition of  class : Definition by Google 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.
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
Classes – Example Account +Owner: Person +Ammount: double +Suspend() +Deposit(sum:double) +Withdraw(sum:double) Class Name Attributes (Properties and Fields) Operations (Methods)
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
Objects – Example 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
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, …)
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
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 using System; ... // Define two variables of type DateTime DateTime today;  DateTime halloween; // Declare and initialize a structure instance DateTime today = DateTime.Now;
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)
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: // Accessing read-only field String empty = String.Empty; // Accessing constant field int maxInt = Int32.MaxValue;
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
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
Accessing Properties and Fields – Example 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));
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
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
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)
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 <object_name>.<method_name>(<parameters>)
Calling Instance Methods –  Examples Calling instance methods of  String : Calling instance methods of  DateTime : 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(&quot;Now: {0}&quot;, now); Console.WriteLine(&quot;8 hours later: {0}&quot;, later);
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 <class_name>.<method_name>(<parameters>)
Calling Static Methods – Examples using System; double radius = 2.9; double area = Math.PI * Math.Pow(radius, 2); Console.WriteLine(&quot;Area: {0}&quot;, area); // Area: 26,4207942166902 double precise = 8.7654321; double round3 = Math.Round(precise, 3); double round1 = Math.Round(precise, 1); Console.WriteLine( &quot;{0}; {1}; {2}&quot;, precise, round3, round1); // 8,7654321; 8,765; 8,8 Constant field Static method Static method Static method
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
Constructors (2) Constructor is invoked by the  new  operator Examples: String s = new String(&quot;Hello!&quot;); // s = &quot;Hello!&quot; <instance_name> = new <class_name>(<parameters>) String s = new String('*', 5); // s = &quot;*****&quot; DateTime dt = new DateTime(2009, 12, 30); DateTime dt = new DateTime(2009, 12, 30, 12, 33, 59); Int32 value = new Int32(1024);
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
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 For example: System  namespace contains  Data  namespace The name of the nested namespace is  System.Data
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 <namespace_name>.<class_name>
Including Namespaces The  using  directive in C#: Allows using types in a namespace, without specifying their full name Example: instead of using <namespace_name> using System; DateTime date; System.DateTime date;
Common Type 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
CTS and Different Languages CTS is common for all .NET languages C#, VB.NET, J#,  JScript.NET , ... CTS type mappings: 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
Value and Reference Types 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
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[]
Exceptions Handling The Paradigm of Exceptions in OOP
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
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 try { // Do some work that can raise an exception } catch (SomeException) { // Handle the caught exception }
Handling Exceptions – Example static void Main() { string s = Console.ReadLine(); try { Int32.Parse(s); Console.WriteLine( &quot;You entered valid Int32 number {0}.&quot;, s); } catch  (FormatException) { Console.WriteLine(&quot;Invalid integer number!&quot;); } catch  (OverflowException) { Console.WriteLine( &quot;The number is too big to fit in Int32!&quot;); } }
The   System.Exception  Class Exceptions in  .NET  are objects The   System.Exception   class is base for all 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 )
Exception Properties – Example class ExceptionsTest { public static void CauseFormatException() { string s = &quot;an invalid number&quot;; Int32.Parse(s); } static void Main() { try { CauseFormatException(); } catch (FormatException fe) { Console.Error.WriteLine(&quot;Exception caught:   {0}\n{1}&quot;, fe.Message, fe.StackTrace); } } }
Exception Properties The   Message  property gives brief description of the problem 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
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: 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)
Exception Hierarchy Exceptions in .NET Framework are organized in a hierarchy
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
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 try { // Do some works that can raise an exception } catch (System.ArithmeticException) { // Handle the caught arithmetic exception }
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: try { // Do some works that can raise any exception } catch { // Handle the caught exception }
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
How Exceptions Work? 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 .NET CLR 1. Execute the program 9. Find handler 10. Display error message
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 throw new ArgumentException(&quot;Invalid amount!&quot;); try { Int32.Parse(str); } catch (FormatException fe) { throw new ArgumentException(&quot;Invalid number&quot;, fe); }
Throwing Exceptions – Example public static double Sqrt(double value) { if (value < 0) throw new System.ArgumentOutOfRangeException( &quot;Sqrt for negative numbers is undefined!&quot;); return Math.Sqrt(value); } static void Main() { try { Sqrt(-1); } catch (ArgumentOutOfRangeException ex) { Console.Error.WriteLine(&quot;Error: &quot; + ex.Message); throw; } }
Strings and Text Processing
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: string s = &quot;Hello, C#&quot;; s H e l l o , C #
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
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 ] string s = &quot;Hello!&quot;; int len = s.Length; // len = 6 char ch = s[1]; // ch = 'e' index  =  s[index]  =  0 1 2 3 4 5 H e l l o !
Strings – Example static void Main() { string s =  &quot;Stand up, stand up, Balkan Superman.&quot;; Console.WriteLine(&quot;s = \&quot;{0}\&quot;&quot;, s); Console.WriteLine(&quot;s.Length = {0}&quot;, s.Length); for (int i = 0; i < s.Length; i++) { Console.WriteLine(&quot;s[{0}] = {1}&quot;, i, s[i]); } }
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 string str1; System.String str2; String str3;
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
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 string s; // s is equal to null string s = &quot;I am a string literal!&quot;; string s2 = s; string s = 42.ToString();
Reading and Printing Strings Reading strings from the console Use the method  Console. ReadLine() string s = Console.ReadLine(); Console.Write(&quot;Please enter your name: &quot;);  string name = Console.ReadLine(); Console.Write(&quot;Hello, {0}! &quot;, name); Console.WriteLine(&quot;Welcome to our party!&quot;); Printing strings to the console Use the methods Write() and  WriteLine()
Comparing Strings A number of ways exist to compare two strings: Dictionary-based string comparison Case-insensitive Case-sensitive 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  Finding the first string in a lexicographical order from a given list of strings: string[] towns = {&quot;Sofia&quot;, &quot;Varna&quot;, &quot;Plovdiv&quot;, &quot;Pleven&quot;, &quot;Bourgas&quot;, &quot;Rousse&quot;, &quot;Yambol&quot;}; 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(&quot;First town: {0}&quot;, firstTown);
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 string str = String.Concat(str1, str2);  string str = str1 + str2 + str3; string str += str1; string name = &quot;Peter&quot;; int age = 22; string s = name + &quot; &quot; + age; //    &quot;Peter 22&quot;
Searching in Strings Finding a character or substring within given string First occurrence First occurrence starting at given position Last occurrence IndexOf(string str) IndexOf(string str, int startIndex) LastIndexOf(string)
Searching in Strings – Example string str = &quot;C# Programming Course&quot;; int index = str.IndexOf(&quot;C#&quot;); // index = 0 index = str.IndexOf(&quot;Course&quot;); // index = 15 index = str.IndexOf(&quot;COURSE&quot;); // index = -1 // IndexOf is case-sensetive. -1 means not found index = str.IndexOf(&quot;ram&quot;); // index = 7 index = str.IndexOf(&quot;r&quot;); // index = 4 index = str.IndexOf(&quot;r&quot;, 5); // index = 7 index = str.IndexOf(&quot;r&quot;, 8); // index = 18 index  =  s[index]  =  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 …
Extracting Substrings Extracting substrings str.Substring(int startIndex, int length) str.Substring(int startIndex) string filename = @&quot;C:\Pics\Rila2009.jpg&quot;; string name = filename.Substring(8, 8); // name is Rila2009 string filename = @&quot;C:\Pics\Summer2009.jpg&quot;; 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 To split a string by given separator(s) use the following method: Example: string[] Split(params char[]) string listOfBeers = &quot;Amstel, Zagorka, Tuborg, Becks.&quot;; string[] beers =  listOfBeers.Split(' ', ',', '.'); Console.WriteLine(&quot;Available beers are:&quot;); foreach (string beer in beers) { Console.WriteLine(beer); }
Replacing and Deleting Substrings Replace(string,   string)  – replaces all occurrences of given string with another The result is new string (strings are immutable) Re move ( index ,   length )  – deletes part of a string and produces new string as result string cocktail = &quot;Vodka + Martini + Cherry&quot;; string replaced = cocktail.Replace(&quot;+&quot;, &quot;and&quot;); // Vodka and Martini and Cherry string price = &quot;$ 1234567&quot;; string lowPrice = price.Remove(2, 3); // $ 4567
Changing Character Casing Using method  ToLower() Using method  ToUpper() string alpha = &quot;aBcDeFg&quot;; string lowerAlpha = alpha.ToLower(); // abcdefg Console.WriteLine(lowerAlpha); string alpha = &quot;aBcDeFg&quot;; string upperAlpha = alpha.ToUpper(); // ABCDEFG Console.WriteLine(upperAlpha);
Trimming White Space Using method  Trim() Using method  Trim(chars ) Using  Trim Start ()  and  Trim End () string s = &quot;  example of white space  &quot;; string clean = s.Trim(); Console.WriteLine(clean); string s = &quot; \t\nHello!!! \n&quot;; string clean = s.Trim(' ', ',' ,'!', '\n','\t'); Console.WriteLine(clean); // Hello string s = &quot;  C#  &quot;; string clean = s.TrimStart(); // clean = &quot;C#  &quot;
Constructing Strings Strings are immutable C oncat() ,  R eplace() ,  T rim() , ...  return new string, do not modify the old one Do not use &quot; + &quot; for strings in a loop! It runs very, very inefficiently! public static string DupChar(char ch, int count) { string result = &quot;&quot;; for (int i=0; i<count; i++) result += ch; return result; } Very bad practice. Avoid this!
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 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  StringBuilde r Class StringBuilder  keeps a buffer memory, allocated in advance Most operations use the buffer memory and do not allocate new objects StringBuilder : Length =9 Capacity =15 Capacity used buffer ( Length ) unused buffer H e l l o , C # !
StringBuilder  – Example Extracting all capital letters from a string 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(); }
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 int number = 5; string s = &quot;The number is &quot; + number.ToString(); Console.WriteLine(s); // The number is 5
Method  ToString(format ) We can apply specific formatting when converting objects to string ToString(fo r matString)  method int number = 42; string s = number.ToString(&quot;D5&quot;); // 00042 s = number.ToString(&quot;X&quot;); // 2A // Consider the default culture is Bulgarian s = number.ToString(&quot;C&quot;); // 42,00 лв double d = 0.375; s = d.ToString(&quot;P2&quot;); // 37,50 %
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)
Method  String.Format() Applies  templates  for formatting strings Placeholders are used for dynamic text Like  Console.WriteLine(…) string template = &quot;If I were {0}, I would {1}.&quot;; string sentence1 = String.Format( template, &quot;developer&quot;, &quot;know C#&quot;); Console.WriteLine(sentence1); // If I were developer, I would know C#. string sentence2 = String.Format( template, &quot;elephant&quot;, &quot;weigh 4500 kg&quot;); Console.WriteLine(sentence2); // If I were elephant, I would weigh 4500 kg.
Composite Formatting The placeholders in the composite formatting strings are specified as follows: Examples: {index[,alignment][:formatString]} double d = 0.375; s = String.Format(&quot;{0,10:F5}&quot;, d); // s = &quot;  0,37500&quot; int number = 42; Console.WriteLine(&quot;Dec {0:D} = Hex {1:X}&quot;, number, number); // Dec 42 = Hex 2A
Formatting Dates Dates have 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 DateTime now = DateTime.Now; Console.WriteLine( &quot;Now is {0:d.MM.yyyy HH:mm:ss}&quot;, now); // Now is 31.11.2009 11:30:32
Collection Classes Lists, Trees, Dictionaries
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 &quot; parameterized   types &quot; or &quot; template types &quot; Similar to the templates in C++ Similar to the generics in Java
The  List<T>  Class Implements the abstract data structure  list  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
List<T>  – Simple Example static void Main() { List<string> list = new List<string>(); list.Add(&quot;C#&quot;); list.Add(&quot;Java&quot;); list.Add(&quot;PHP&quot;); foreach (string item in list) { Console.WriteLine(item); } // Result: //  C# //  Java //  PHP }
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
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
Primes in an Interval – Example 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; }
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
Stack<T>  – Example Using  Push() ,  Pop()  and  Peek()  methods static void Main() { Stack<string> stack = new Stack<string>(); stack.Push(&quot;1. Ivan&quot;); stack.Push(&quot;2. Nikolay&quot;); stack.Push(&quot;3. Maria&quot;); stack.Push(&quot;4. George&quot;); Console.WriteLine(&quot;Top = {0}&quot;, stack.Peek()); while (stack.Count > 0) { string personName = stack.Pop(); Console.WriteLine(personName); } }
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
Queue<T>  –   Example Using  Enqueue()  and  Dequeue()  methods static void Main() { Queue<string> queue = new Queue<string>(); queue.Enqueue(&quot;Message One&quot;); queue.Enqueue(&quot;Message Two&quot;); queue.Enqueue(&quot;Message Three&quot;); queue.Enqueue(&quot;Message Four&quot;); while (queue.Count > 0) { string message = queue.Dequeue(); Console.WriteLine(message); } }
Dictionary<TKey,TValue>   Class Implements the abstract data type &quot; Dictionary &quot; as hash table Size is dynamically increased as needed Contains a collection of key-and-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 elements
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
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
Dictionary<TKey,Tvalue>  –  Example Dictionary<string, int> studentsMarks    = new Dictionary<string, int>(); studentsMarks.Add(&quot;Ivan&quot;, 4); studentsMarks.Add(&quot;Peter&quot;, 6); studentsMarks.Add(&quot;Maria&quot;, 6); studentsMarks.Add(&quot;George&quot;, 5); int peterMark = studentsMarks[&quot;Peter&quot;]; Console.WriteLine(&quot;Peter's mark: {0}&quot;, peterMark); Console.WriteLine(&quot;Is Peter in the hash table: {0}&quot;, studentsMarks.ContainsKey(&quot;Peter&quot;)); Console.WriteLine(&quot;Students and grades:&quot;); foreach (var pair in studentsMarks) { Console.WriteLine(&quot;{0} --> {1} &quot;, pair.Key, pair.Value); }
Counting Words in Given Text string text = &quot;Welcome to our C# course. In this &quot; + &quot;course you will learn how to write simple &quot; + &quot;programs in C# and Microsoft .NET&quot;; 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(&quot;{0} --> {1}&quot;, pair.Key, pair.Value); }
Balanced Trees in .NET Balanced Binary Search Trees Ordered binary search trees that have height of  log 2 (n)  where  n  is the number of their nodes Searching costs about  log 2 (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 &quot;Wintellect Power Collections for .NET&quot; are more flexible
Sorted Dictionary – Example  string text = &quot;Welcome to our C# course. In this &quot; + &quot;course you will learn how to write simple &quot; + &quot;programs in C# and Microsoft .NET&quot;; 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(&quot;{0} --> {1}&quot;, pair.Key, pair.Value); }
Attributes What They Are? How and When to Use Them?
What Are Attributes? Special declarative tags 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 and can be manipulated by different tools Instances of classes derived from  System.Attribute
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 [Flags] // System.FlagsAttribute public enum FileAccess  { Read = 1, Write = 2, ReadWrite = Read | Write }
Attributes With Parameters Attributes use parameters for initialization: In the example the  [ DllImport ]  attribute is   instantiated by the compiler   as follows : An object of  System.Runtime. InteropServices.DllImportAttribute   class is created and initialized [DllImport(&quot;user32.dll&quot;, EntryPoint=&quot;MessageBox&quot;)] public static extern int ShowMessageBox(int hWnd, string text, string caption, int type); ... ShowMessageBox(0, &quot;Some text&quot;, &quot;Some caption&quot;, 0);
C# Language Overview (Part II) Questions? http://academy.telerik.com

More Related Content

PPTX
C# overview part 2
PPTX
5. c sharp language overview part ii
PPT
11 Using classes and objects
PDF
Lecture 01 - Basic Concept About OOP With Python
PPTX
Introduce oop in python
PDF
Class and Objects in Java
PPT
Object and class in java
PPT
Class & Object - Intro
C# overview part 2
5. c sharp language overview part ii
11 Using classes and objects
Lecture 01 - Basic Concept About OOP With Python
Introduce oop in python
Class and Objects in Java
Object and class in java
Class & Object - Intro

What's hot (20)

PPT
Defining classes-and-objects-1.0
PPT
Core java
PPT
Object and class
PDF
C# Summer course - Lecture 3
PPTX
Java 103 intro to java data structures
PPTX
javaimplementation
PDF
Option - A Better Way to Handle Null Value
PPTX
Ios development
PDF
The Ring programming language version 1.6 book - Part 182 of 189
PDF
Scala Bootcamp 1
PPTX
Python oop class 1
PDF
Scala cheatsheet
PDF
Scala jargon cheatsheet
PPT
PDF
Scala collections api expressivity and brevity upgrade from java
PPT
Core java concepts
PPTX
Scala for curious
PPTX
Python oop - class 2 (inheritance)
PPTX
Python - OOP Programming
PPTX
Core java concepts
Defining classes-and-objects-1.0
Core java
Object and class
C# Summer course - Lecture 3
Java 103 intro to java data structures
javaimplementation
Option - A Better Way to Handle Null Value
Ios development
The Ring programming language version 1.6 book - Part 182 of 189
Scala Bootcamp 1
Python oop class 1
Scala cheatsheet
Scala jargon cheatsheet
Scala collections api expressivity and brevity upgrade from java
Core java concepts
Scala for curious
Python oop - class 2 (inheritance)
Python - OOP Programming
Core java concepts
Ad

Similar to C# Language Overview Part II (20)

PPT
Using class and object java
PPT
Visula C# Programming Lecture 6
PPT
Csharp_mahesh
PPTX
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
PPT
Introduction to csharp
PPT
Introduction to csharp
PPT
Introduction to-csharp-1229579367461426-1
PPT
Introduction To Csharp
PPT
Introduction to csharp
PPS
Introduction to CSharp
PPT
Synapseindia dot net development
PPT
14. Defining Classes
PPT
Advanced c#
PDF
oblect oriented programming language in java notes .pdf
ODP
James Jesus Bermas on Crash Course on Python
PPTX
Reflection in C#
PDF
Introduction to C++
PPT
9781439035665 ppt ch08
Using class and object java
Visula C# Programming Lecture 6
Csharp_mahesh
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
Introduction to csharp
Introduction to csharp
Introduction to-csharp-1229579367461426-1
Introduction To Csharp
Introduction to csharp
Introduction to CSharp
Synapseindia dot net development
14. Defining Classes
Advanced c#
oblect oriented programming language in java notes .pdf
James Jesus Bermas on Crash Course on Python
Reflection in C#
Introduction to C++
9781439035665 ppt ch08
Ad

More from Doncho Minkov (20)

PDF
Web Design Concepts
PPT
Web design Tools
PPT
PPT
HTML 5 Tables and Forms
PPT
CSS Overview
PPT
CSS Presentation
PPT
CSS Layout
PPT
PPT
Adobe Photoshop
PPT
Slice and Dice
PPT
Introduction to XAML and WPF
PPT
WPF Layout Containers
PPT
WPF Controls
PPT
WPF Templating and Styling
PPT
WPF Graphics and Animations
PPT
Simple Data Binding
PPT
Complex Data Binding
PPT
WPF Concepts
PPT
Model View ViewModel
PPT
WPF and Databases
Web Design Concepts
Web design Tools
HTML 5 Tables and Forms
CSS Overview
CSS Presentation
CSS Layout
Adobe Photoshop
Slice and Dice
Introduction to XAML and WPF
WPF Layout Containers
WPF Controls
WPF Templating and Styling
WPF Graphics and Animations
Simple Data Binding
Complex Data Binding
WPF Concepts
Model View ViewModel
WPF and Databases

Recently uploaded (20)

PDF
Empathic Computing: Creating Shared Understanding
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPT
Teaching material agriculture food technology
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
Encapsulation theory and applications.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Unlocking AI with Model Context Protocol (MCP)
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Modernizing your data center with Dell and AMD
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
Empathic Computing: Creating Shared Understanding
Advanced methodologies resolving dimensionality complications for autism neur...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Understanding_Digital_Forensics_Presentation.pptx
Teaching material agriculture food technology
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Electronic commerce courselecture one. Pdf
Encapsulation theory and applications.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Unlocking AI with Model Context Protocol (MCP)
“AI and Expert System Decision Support & Business Intelligence Systems”
Modernizing your data center with Dell and AMD
Spectral efficient network and resource selection model in 5G networks
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Encapsulation_ Review paper, used for researhc scholars

C# Language Overview Part II

  • 1. C# Language Overview (Part II) Creating and Using Objects, Exceptions, Strings, Generics, Collections, Attributes Doncho Minkov Telerik School Academy schoolacademy.telerik.com Technical Trainer http://www.minkov.it
  • 2. Table of Contents Creating and Using Objects Exceptions Handling Strings and Text Processing Generics Collection Classes Attributes
  • 3. Using Classes and Objects Using the Standard .NET Framework Classes
  • 4. What is Class? The formal definition of class : Definition by Google 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
  • 6. Classes – Example 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
  • 8. Objects – Example Account +Owner: Person +Ammount: double +Suspend() +Deposit(sum:double) +Withdraw(sum:double) Class ivanAccount +Owner=&quot;Ivan Kolev&quot; +Ammount=5000.0 peterAccount +Owner=&quot;Peter Kirov&quot; +Ammount=1825.33 kirilAccount +Owner=&quot;Kiril Kirov&quot; +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, …)
  • 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
  • 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 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 &quot;&quot; string)
  • 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: // 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
  • 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
  • 16. Accessing Properties and Fields – Example using System; ... DateTime christmas = new DateTime(2009, 12, 25); int day = christmas.Day; int month = christmas.Month; int year = christmas.Year; Console.WriteLine( &quot;Christmas day: {0}, month: {1}, year: {2}&quot;, day, month, year); Console.WriteLine( &quot;Day of year: {0}&quot;, christmas.DayOfYear); Console.WriteLine(&quot;Is {0} leap year: {1}&quot;, 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
  • 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
  • 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)
  • 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 <object_name>.<method_name>(<parameters>)
  • 21. Calling Instance Methods – Examples Calling instance methods of String : Calling instance methods of DateTime : 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(&quot;Now: {0}&quot;, now); Console.WriteLine(&quot;8 hours later: {0}&quot;, later);
  • 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 <class_name>.<method_name>(<parameters>)
  • 23. Calling Static Methods – Examples using System; double radius = 2.9; double area = Math.PI * Math.Pow(radius, 2); Console.WriteLine(&quot;Area: {0}&quot;, area); // Area: 26,4207942166902 double precise = 8.7654321; double round3 = Math.Round(precise, 3); double round1 = Math.Round(precise, 1); Console.WriteLine( &quot;{0}; {1}; {2}&quot;, precise, round3, round1); // 8,7654321; 8,765; 8,8 Constant field Static method Static method Static method
  • 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
  • 25. Constructors (2) Constructor is invoked by the new operator Examples: String s = new String(&quot;Hello!&quot;); // s = &quot;Hello!&quot; <instance_name> = new <class_name>(<parameters>) String s = new String('*', 5); // s = &quot;*****&quot; 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
  • 27. 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 For example: System namespace contains Data namespace The name of the nested namespace is System.Data
  • 28. 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 <namespace_name>.<class_name>
  • 29. Including Namespaces The using directive in C#: Allows using types in a namespace, without specifying their full name Example: instead of using <namespace_name> using System; DateTime date; System.DateTime date;
  • 30. Common Type 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. CTS and Different Languages CTS is common for all .NET languages C#, VB.NET, J#, JScript.NET , ... CTS type mappings: 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
  • 32. Value and Reference Types 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. 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. Exceptions Handling The Paradigm of Exceptions in OOP
  • 35. 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. 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 try { // Do some work that can raise an exception } catch (SomeException) { // Handle the caught exception }
  • 37. Handling Exceptions – Example static void Main() { string s = Console.ReadLine(); try { Int32.Parse(s); Console.WriteLine( &quot;You entered valid Int32 number {0}.&quot;, s); } catch (FormatException) { Console.WriteLine(&quot;Invalid integer number!&quot;); } catch (OverflowException) { Console.WriteLine( &quot;The number is too big to fit in Int32!&quot;); } }
  • 38. The System.Exception Class Exceptions in .NET are objects The System.Exception class is base for all 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 )
  • 39. Exception Properties – Example class ExceptionsTest { public static void CauseFormatException() { string s = &quot;an invalid number&quot;; Int32.Parse(s); } static void Main() { try { CauseFormatException(); } catch (FormatException fe) { Console.Error.WriteLine(&quot;Exception caught: {0}\n{1}&quot;, fe.Message, fe.StackTrace); } } }
  • 40. Exception Properties The Message property gives brief description of the problem 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
  • 41. 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: 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)
  • 42. Exception Hierarchy Exceptions in .NET Framework are organized in a hierarchy
  • 43. 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. 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 try { // Do some works that can raise an exception } catch (System.ArithmeticException) { // Handle the caught arithmetic exception }
  • 45. 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: try { // Do some works that can raise any exception } catch { // Handle the caught exception }
  • 46. 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. How Exceptions Work? 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 .NET CLR 1. Execute the program 9. Find handler 10. Display error message
  • 48. 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 throw new ArgumentException(&quot;Invalid amount!&quot;); try { Int32.Parse(str); } catch (FormatException fe) { throw new ArgumentException(&quot;Invalid number&quot;, fe); }
  • 49. Throwing Exceptions – Example public static double Sqrt(double value) { if (value < 0) throw new System.ArgumentOutOfRangeException( &quot;Sqrt for negative numbers is undefined!&quot;); return Math.Sqrt(value); } static void Main() { try { Sqrt(-1); } catch (ArgumentOutOfRangeException ex) { Console.Error.WriteLine(&quot;Error: &quot; + ex.Message); throw; } }
  • 50. Strings and Text Processing
  • 51. 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: string s = &quot;Hello, C#&quot;; s H e l l o , C #
  • 52. 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. 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 ] string s = &quot;Hello!&quot;; int len = s.Length; // len = 6 char ch = s[1]; // ch = 'e' index = s[index] = 0 1 2 3 4 5 H e l l o !
  • 54. Strings – Example static void Main() { string s = &quot;Stand up, stand up, Balkan Superman.&quot;; Console.WriteLine(&quot;s = \&quot;{0}\&quot;&quot;, s); Console.WriteLine(&quot;s.Length = {0}&quot;, s.Length); for (int i = 0; i < s.Length; i++) { Console.WriteLine(&quot;s[{0}] = {1}&quot;, i, s[i]); } }
  • 55. 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 string str1; System.String str2; String str3;
  • 56. 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. 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 string s; // s is equal to null string s = &quot;I am a string literal!&quot;; string s2 = s; string s = 42.ToString();
  • 58. Reading and Printing Strings Reading strings from the console Use the method Console. ReadLine() string s = Console.ReadLine(); Console.Write(&quot;Please enter your name: &quot;); string name = Console.ReadLine(); Console.Write(&quot;Hello, {0}! &quot;, name); Console.WriteLine(&quot;Welcome to our party!&quot;); Printing strings to the console Use the methods Write() and WriteLine()
  • 59. Comparing Strings A number of ways exist to compare two strings: Dictionary-based string comparison Case-insensitive Case-sensitive 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);
  • 60. Comparing Strings – Example Finding the first string in a lexicographical order from a given list of strings: string[] towns = {&quot;Sofia&quot;, &quot;Varna&quot;, &quot;Plovdiv&quot;, &quot;Pleven&quot;, &quot;Bourgas&quot;, &quot;Rousse&quot;, &quot;Yambol&quot;}; 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(&quot;First town: {0}&quot;, firstTown);
  • 61. 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 string str = String.Concat(str1, str2); string str = str1 + str2 + str3; string str += str1; string name = &quot;Peter&quot;; int age = 22; string s = name + &quot; &quot; + age; //  &quot;Peter 22&quot;
  • 62. Searching in Strings Finding a character or substring within given string First occurrence First occurrence starting at given position Last occurrence IndexOf(string str) IndexOf(string str, int startIndex) LastIndexOf(string)
  • 63. Searching in Strings – Example string str = &quot;C# Programming Course&quot;; int index = str.IndexOf(&quot;C#&quot;); // index = 0 index = str.IndexOf(&quot;Course&quot;); // index = 15 index = str.IndexOf(&quot;COURSE&quot;); // index = -1 // IndexOf is case-sensetive. -1 means not found index = str.IndexOf(&quot;ram&quot;); // index = 7 index = str.IndexOf(&quot;r&quot;); // index = 4 index = str.IndexOf(&quot;r&quot;, 5); // index = 7 index = str.IndexOf(&quot;r&quot;, 8); // index = 18 index = s[index] = 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 …
  • 64. Extracting Substrings Extracting substrings str.Substring(int startIndex, int length) str.Substring(int startIndex) string filename = @&quot;C:\Pics\Rila2009.jpg&quot;; string name = filename.Substring(8, 8); // name is Rila2009 string filename = @&quot;C:\Pics\Summer2009.jpg&quot;; 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
  • 65. Splitting Strings To split a string by given separator(s) use the following method: Example: string[] Split(params char[]) string listOfBeers = &quot;Amstel, Zagorka, Tuborg, Becks.&quot;; string[] beers = listOfBeers.Split(' ', ',', '.'); Console.WriteLine(&quot;Available beers are:&quot;); foreach (string beer in beers) { Console.WriteLine(beer); }
  • 66. Replacing and Deleting Substrings Replace(string, string) – replaces all occurrences of given string with another The result is new string (strings are immutable) Re move ( index , length ) – deletes part of a string and produces new string as result string cocktail = &quot;Vodka + Martini + Cherry&quot;; string replaced = cocktail.Replace(&quot;+&quot;, &quot;and&quot;); // Vodka and Martini and Cherry string price = &quot;$ 1234567&quot;; string lowPrice = price.Remove(2, 3); // $ 4567
  • 67. Changing Character Casing Using method ToLower() Using method ToUpper() string alpha = &quot;aBcDeFg&quot;; string lowerAlpha = alpha.ToLower(); // abcdefg Console.WriteLine(lowerAlpha); string alpha = &quot;aBcDeFg&quot;; string upperAlpha = alpha.ToUpper(); // ABCDEFG Console.WriteLine(upperAlpha);
  • 68. Trimming White Space Using method Trim() Using method Trim(chars ) Using Trim Start () and Trim End () string s = &quot; example of white space &quot;; string clean = s.Trim(); Console.WriteLine(clean); string s = &quot; \t\nHello!!! \n&quot;; string clean = s.Trim(' ', ',' ,'!', '\n','\t'); Console.WriteLine(clean); // Hello string s = &quot; C# &quot;; string clean = s.TrimStart(); // clean = &quot;C# &quot;
  • 69. Constructing Strings Strings are immutable C oncat() , R eplace() , T rim() , ... return new string, do not modify the old one Do not use &quot; + &quot; for strings in a loop! It runs very, very inefficiently! public static string DupChar(char ch, int count) { string result = &quot;&quot;; for (int i=0; i<count; i++) result += ch; return result; } Very bad practice. Avoid this!
  • 70. 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 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(); }
  • 71. The StringBuilde r Class StringBuilder keeps a buffer memory, allocated in advance Most operations use the buffer memory and do not allocate new objects StringBuilder : Length =9 Capacity =15 Capacity used buffer ( Length ) unused buffer H e l l o , C # !
  • 72. StringBuilder – Example Extracting all capital letters from a string 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(); }
  • 73. 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 int number = 5; string s = &quot;The number is &quot; + number.ToString(); Console.WriteLine(s); // The number is 5
  • 74. Method ToString(format ) We can apply specific formatting when converting objects to string ToString(fo r matString) method int number = 42; string s = number.ToString(&quot;D5&quot;); // 00042 s = number.ToString(&quot;X&quot;); // 2A // Consider the default culture is Bulgarian s = number.ToString(&quot;C&quot;); // 42,00 лв double d = 0.375; s = d.ToString(&quot;P2&quot;); // 37,50 %
  • 75. 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. Method String.Format() Applies templates for formatting strings Placeholders are used for dynamic text Like Console.WriteLine(…) string template = &quot;If I were {0}, I would {1}.&quot;; string sentence1 = String.Format( template, &quot;developer&quot;, &quot;know C#&quot;); Console.WriteLine(sentence1); // If I were developer, I would know C#. string sentence2 = String.Format( template, &quot;elephant&quot;, &quot;weigh 4500 kg&quot;); Console.WriteLine(sentence2); // If I were elephant, I would weigh 4500 kg.
  • 77. Composite Formatting The placeholders in the composite formatting strings are specified as follows: Examples: {index[,alignment][:formatString]} double d = 0.375; s = String.Format(&quot;{0,10:F5}&quot;, d); // s = &quot; 0,37500&quot; int number = 42; Console.WriteLine(&quot;Dec {0:D} = Hex {1:X}&quot;, number, number); // Dec 42 = Hex 2A
  • 78. Formatting Dates Dates have 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 DateTime now = DateTime.Now; Console.WriteLine( &quot;Now is {0:d.MM.yyyy HH:mm:ss}&quot;, now); // Now is 31.11.2009 11:30:32
  • 79. Collection Classes Lists, Trees, Dictionaries
  • 80. 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 &quot; parameterized types &quot; or &quot; template types &quot; Similar to the templates in C++ Similar to the generics in Java
  • 81. The List<T> Class Implements the abstract data structure list 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
  • 82. List<T> – Simple Example static void Main() { List<string> list = new List<string>(); list.Add(&quot;C#&quot;); list.Add(&quot;Java&quot;); list.Add(&quot;PHP&quot;); foreach (string item in list) { Console.WriteLine(item); } // Result: // C# // Java // PHP }
  • 83. 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. 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. Primes in an Interval – Example 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; }
  • 86. 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. Stack<T> – Example Using Push() , Pop() and Peek() methods static void Main() { Stack<string> stack = new Stack<string>(); stack.Push(&quot;1. Ivan&quot;); stack.Push(&quot;2. Nikolay&quot;); stack.Push(&quot;3. Maria&quot;); stack.Push(&quot;4. George&quot;); Console.WriteLine(&quot;Top = {0}&quot;, stack.Peek()); while (stack.Count > 0) { string personName = stack.Pop(); Console.WriteLine(personName); } }
  • 88. 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. Queue<T> – Example Using Enqueue() and Dequeue() methods static void Main() { Queue<string> queue = new Queue<string>(); queue.Enqueue(&quot;Message One&quot;); queue.Enqueue(&quot;Message Two&quot;); queue.Enqueue(&quot;Message Three&quot;); queue.Enqueue(&quot;Message Four&quot;); while (queue.Count > 0) { string message = queue.Dequeue(); Console.WriteLine(message); } }
  • 90. Dictionary<TKey,TValue> Class Implements the abstract data type &quot; Dictionary &quot; as hash table Size is dynamically increased as needed Contains a collection of key-and-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 elements
  • 91. 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. 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. Dictionary<TKey,Tvalue> – Example Dictionary<string, int> studentsMarks = new Dictionary<string, int>(); studentsMarks.Add(&quot;Ivan&quot;, 4); studentsMarks.Add(&quot;Peter&quot;, 6); studentsMarks.Add(&quot;Maria&quot;, 6); studentsMarks.Add(&quot;George&quot;, 5); int peterMark = studentsMarks[&quot;Peter&quot;]; Console.WriteLine(&quot;Peter's mark: {0}&quot;, peterMark); Console.WriteLine(&quot;Is Peter in the hash table: {0}&quot;, studentsMarks.ContainsKey(&quot;Peter&quot;)); Console.WriteLine(&quot;Students and grades:&quot;); foreach (var pair in studentsMarks) { Console.WriteLine(&quot;{0} --> {1} &quot;, pair.Key, pair.Value); }
  • 94. Counting Words in Given Text string text = &quot;Welcome to our C# course. In this &quot; + &quot;course you will learn how to write simple &quot; + &quot;programs in C# and Microsoft .NET&quot;; 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(&quot;{0} --> {1}&quot;, pair.Key, pair.Value); }
  • 95. Balanced Trees in .NET Balanced Binary Search Trees Ordered binary search trees that have height of log 2 (n) where n is the number of their nodes Searching costs about log 2 (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 &quot;Wintellect Power Collections for .NET&quot; are more flexible
  • 96. Sorted Dictionary – Example string text = &quot;Welcome to our C# course. In this &quot; + &quot;course you will learn how to write simple &quot; + &quot;programs in C# and Microsoft .NET&quot;; 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(&quot;{0} --> {1}&quot;, pair.Key, pair.Value); }
  • 97. Attributes What They Are? How and When to Use Them?
  • 98. What Are Attributes? Special declarative tags 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 and can be manipulated by different tools Instances of classes derived from System.Attribute
  • 99. 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 [Flags] // System.FlagsAttribute public enum FileAccess { Read = 1, Write = 2, ReadWrite = Read | Write }
  • 100. Attributes With Parameters Attributes use parameters for initialization: In the example the [ DllImport ] attribute is instantiated by the compiler as follows : An object of System.Runtime. InteropServices.DllImportAttribute class is created and initialized [DllImport(&quot;user32.dll&quot;, EntryPoint=&quot;MessageBox&quot;)] public static extern int ShowMessageBox(int hWnd, string text, string caption, int type); ... ShowMessageBox(0, &quot;Some text&quot;, &quot;Some caption&quot;, 0);
  • 101. C# Language Overview (Part II) Questions? http://academy.telerik.com

Editor's Notes

  • #5: * 07/16/96 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #25: * 07/16/96 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #26: * 07/16/96 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #35: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #36: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #37: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #41: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #42: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #43: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #44: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #45: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #46: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #47: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #49: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #50: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #51: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #71: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ## Introducing the StringBuffer Class StringBuffer represents strings that can be modified and extended at run time. The following example creates three new String objects, and copies all the characters each time a new String is created: String quote = &amp;quot;Fasten your seatbelts, &amp;quot;; quote = quote + &amp;quot;it’s going to be a bumpy night.&amp;quot;; It is more efficient to preallocate the amount of space required using the StringBuffer constructor, and its append() method as follows: StringBuffer quote = new StringBuffer(60); // alloc 60 chars quote.append(&amp;quot;Fasten your seatbelts, &amp;quot;); quote.append(&amp;quot; it’s going to be a bumpy night. &amp;quot;); StringBuffer also provides a number of overloaded insert() methods for inserting various types of data at a particular location in the string buffer. Instructor Note The example in the slide uses StringBuffer to reverse the characters in a string. A StringBuffer object is created, with the same length as the string. The loop traverses the String parameter in reverse order and appends each of its characters to the StringBuffer object by using append() . The StringBuffer therefore holds a reverse copy of the String parameter. At the end of the method, a new String object is created from the StringBuffer object, and this String is returned from the method .
  • #80: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #98: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #99: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #100: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #101: * (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##