C# Language Overview (Part II) Creating and Using Objects, Exceptions, Strings, Generics, Collections, Attributes Doncho M...
Table of Contents <ul><li>Creating and Using Objects </li></ul><ul><li>Exceptions Handling </li></ul><ul><li>Strings and T...
Using Classes and Objects Using the Standard .NET Framework Classes
What is Class? <ul><li>The formal definition of  class : </li></ul><ul><li>Definition by Google </li></ul>Classes  act as ...
Classes <ul><li>Classes provide the structure for objects </li></ul><ul><ul><li>Define their prototype, act as template </...
Classes – Example Account +Owner: Person +Ammount: double +Suspend() +Deposit(sum:double) +Withdraw(sum:double) Class Name...
Objects <ul><li>An  object  is a concrete  instance  of a particular class  </li></ul><ul><li>Creating an object from a cl...
Objects – Example Account +Owner: Person +Ammount: double +Suspend() +Deposit(sum:double) +Withdraw(sum:double) Class ivan...
Classes in C# <ul><li>Basic units that compose programs </li></ul><ul><li>Implementation is  encapsulated  (hidden)  </li>...
Classes in C# – Examples <ul><li>Example of classes: </li></ul><ul><ul><li>System.Console </li></ul></ul><ul><ul><li>Syste...
Declaring Objects <ul><li>An instance of a class or structure can be defined like any other variable: </li></ul><ul><li>In...
Fields <ul><li>Fields are data members of a class </li></ul><ul><li>Can be variables and constants </li></ul><ul><li>Acces...
Accessing Fields <ul><li>Constant fields can be only read </li></ul><ul><li>Variable fields can be read and modified </li>...
Properties <ul><li>Properties look like fields (have name and type), but they can contain code, executed when they are acc...
Properties (2) <ul><li>According to the implemented accessors properties can be: </li></ul><ul><ul><li>Read-only ( get  ac...
Accessing Properties and Fields – Example using System; ... DateTime christmas = new DateTime(2009, 12, 25); int day = chr...
Instance and Static Members <ul><li>Fields, properties and methods can be: </li></ul><ul><ul><li>Instance  (or object memb...
Instance and Static Members – Examples <ul><li>Example of instance member </li></ul><ul><ul><li>String.Length </li></ul></...
Methods <ul><li>Methods manipulate the data of the object to which they belong or perform other tasks </li></ul><ul><li>Ex...
Instance Methods <ul><li>Instance methods manipulate the data of a specified object or perform any other tasks </li></ul><...
Calling Instance Methods –  Examples <ul><li>Calling instance methods of  String : </li></ul><ul><li>Calling instance meth...
Static Methods <ul><li>Static methods are common for all instances of a class (shared between all instances) </li></ul><ul...
Calling Static Methods – Examples using System; double radius = 2.9; double area = Math.PI * Math.Pow(radius, 2); Console....
Constructors <ul><li>Constructors are special methods used to assign initial values of the fields in an object </li></ul><...
Constructors (2) <ul><li>Constructor is invoked by the  new  operator </li></ul><ul><li>Examples: </li></ul>String s = new...
Structures <ul><li>Structures are similar to classes </li></ul><ul><li>Structures are usually used for storing data struct...
What is a Namespace? <ul><li>Namespaces are used to organize the source code into more logical and manageable way </li></u...
Full Class Names <ul><li>A full name of a class is the name of the class preceded by the name of its namespace </li></ul><...
Including Namespaces <ul><li>The  using  directive in C#: </li></ul><ul><li>Allows using types in a namespace, without spe...
Common Type System (CTS) <ul><li>CTS defines all data  types  supported in .NET Framework </li></ul><ul><ul><li>Primitive ...
CTS and Different Languages <ul><li>CTS is common for all .NET languages </li></ul><ul><ul><li>C#, VB.NET, J#,  JScript.NE...
Value and Reference Types <ul><li>In CTS there are two categories of types </li></ul><ul><ul><li>Value   types </li></ul><...
Value and Reference Types – Examples <ul><li>Value types </li></ul><ul><ul><li>Most of the primitive types </li></ul></ul>...
Exceptions Handling The Paradigm of Exceptions in OOP
What are Exceptions? <ul><li>The exceptions in .NET Framework are classic implementation of the OOP exception model </li><...
Handling Exceptions <ul><li>In C# the exceptions can be handled by the   try-catch-finally  construction </li></ul><ul><li...
Handling Exceptions – Example static void Main() { string s = Console.ReadLine(); try { Int32.Parse(s); Console.WriteLine(...
The   System.Exception  Class <ul><li>Exceptions in  .NET  are objects </li></ul><ul><li>The   System.Exception   class is...
Exception Properties – Example class ExceptionsTest { public static void CauseFormatException() { string s = &quot;an inva...
Exception Properties <ul><li>The   Message  property gives brief description of the problem </li></ul><ul><li>The   StackT...
Exception Properties (2) <ul><li>File names and line numbers are accessible only if the compilation was in  Debug  mode </...
Exception Hierarchy <ul><li>Exceptions in .NET Framework are organized in a hierarchy </li></ul>
Types of Exceptions <ul><li>All .NET exceptions inherit from  System.Exception </li></ul><ul><li>The system exceptions inh...
Handling Exceptions <ul><li>When catching an exception of a particular class, all its inheritors (child exceptions) are ca...
Handling All Exceptions <ul><li>All exceptions thrown by .NET managed code inherit the  System.Exception  exception </li><...
Throwing Exceptions <ul><li>Exceptions are thrown (raised) by  throw  keyword in C# </li></ul><ul><ul><li>Used to notify t...
How Exceptions Work? Main() Method 1 Method 2 Method N 2. Method call 3. Method call 4. Method call … Main() Method 1 Meth...
Using  throw  Keyword <ul><li>Throwing an exception with error message: </li></ul><ul><li>Exceptions can take message and ...
Throwing Exceptions – Example public static double Sqrt(double value) { if (value < 0) throw new System.ArgumentOutOfRange...
Strings and Text Processing
What Is String? <ul><li>Strings are sequences of characters </li></ul><ul><li>Each character is a Unicode symbol </li></ul...
The  System.String  Class <ul><li>Strings are represented by  System.String  objects in .NET Framework </li></ul><ul><ul><...
The  System.String  Class (2) <ul><li>String objects are like arrays of characters ( char[] ) </li></ul><ul><ul><li>Have f...
Strings – Example static void Main() { string s =  &quot;Stand up, stand up, Balkan Superman.&quot;; Console.WriteLine(&qu...
Declaring Strings <ul><li>There are two ways of declaring string variables: </li></ul><ul><ul><li>Using   the  C#  keyword...
Creating Strings <ul><li>Before initializing a string variable has  null   value </li></ul><ul><li>Strings can be initiali...
Creating Strings (2) <ul><li>Not initialized variables has value of  null </li></ul><ul><li>Assigning a string literal </l...
Reading and Printing Strings <ul><li>Reading strings from the console </li></ul><ul><ul><li>Use the method  Console. ReadL...
Comparing Strings <ul><li>A number of ways exist to compare two strings: </li></ul><ul><ul><li>Dictionary-based string com...
Comparing Strings – Example  <ul><li>Finding the first string in a lexicographical order from a given list of strings: </l...
Concatenating Strings <ul><li>There are two ways to combine strings: </li></ul><ul><ul><li>Using the  Concat()  method </l...
Searching in Strings <ul><li>Finding a character or substring within given string </li></ul><ul><ul><li>First occurrence <...
Searching in Strings – Example string str = &quot;C# Programming Course&quot;; int index = str.IndexOf(&quot;C#&quot;); //...
Extracting Substrings <ul><li>Extracting substrings </li></ul><ul><ul><li>str.Substring(int startIndex, int length) </li><...
Splitting Strings <ul><li>To split a string by given separator(s) use the following method: </li></ul><ul><li>Example: </l...
Replacing and Deleting Substrings <ul><li>Replace(string,   string)  – replaces all occurrences of given string with anoth...
Changing Character Casing <ul><li>Using method  ToLower() </li></ul><ul><li>Using method  ToUpper() </li></ul>string alpha...
Trimming White Space <ul><li>Using method  Trim() </li></ul><ul><li>Using method  Trim(chars ) </li></ul><ul><li>Using  Tr...
Constructing Strings <ul><li>Strings are immutable </li></ul><ul><ul><li>C oncat() ,  R eplace() ,  T rim() , ...  return ...
Changing the Contents of a String –  StringBuilder <ul><li>Use the  System.Text.StringBuilder  class for modifiable string...
The  StringBuilde r Class <ul><li>StringBuilder  keeps a buffer memory, allocated in advance </li></ul><ul><ul><li>Most op...
StringBuilder  – Example <ul><li>Extracting all capital letters from a string </li></ul>public static string ExtractCapita...
Method  ToString() <ul><li>All classes have public virtual method  ToString() </li></ul><ul><ul><li>Returns a human-readab...
Method  ToString(format ) <ul><li>We can apply specific formatting when converting objects to string </li></ul><ul><ul><li...
Formatting Strings <ul><li>The formatting strings are different for the different types </li></ul><ul><li>Some formatting ...
Method  String.Format() <ul><li>Applies  templates  for formatting strings </li></ul><ul><ul><li>Placeholders are used for...
Composite Formatting <ul><li>The placeholders in the composite formatting strings are specified as follows: </li></ul><ul>...
Formatting Dates <ul><li>Dates have their own formatting strings </li></ul><ul><ul><li>d ,  dd  –  day (with/without leadi...
Collection Classes Lists, Trees, Dictionaries
What are Generics? <ul><li>Generics allow defining parameterized classes that process data of unknown (generic) type </li>...
The  List<T>  Class <ul><li>Implements the abstract data structure  list  using an array  </li></ul><ul><ul><li>All elemen...
List<T>  – Simple Example static void Main() { List<string> list = new List<string>(); list.Add(&quot;C#&quot;); list.Add(...
List<T>  – Functionality <ul><li>list[index]  – access element by index </li></ul><ul><li>Insert(index ,   T)  – inserts g...
List<T>  – Functionality (2) <ul><li>IndexOf()  – returns the index of the first occurrence of a value   in the list  ( ze...
Primes in an Interval – Example static List<int> FindPrimes(int start, int end) { List<int> primesList = new List<int>(); ...
The  Stack<T>  Class <ul><li>Implements the  stack  data structure using an array </li></ul><ul><ul><li>Elements are of th...
Stack<T>  – Example <ul><li>Using  Push() ,  Pop()  and  Peek()  methods </li></ul>static void Main() { Stack<string> stac...
The  Queue<T>  Class <ul><li>Implements the queue data structure using a circular resizable array </li></ul><ul><ul><li>El...
Queue<T>  –   Example <ul><li>Using  Enqueue()  and  Dequeue()  methods </li></ul>static void Main() { Queue<string> queue...
Dictionary<TKey,TValue>   Class <ul><li>Implements the abstract data type &quot; Dictionary &quot; as hash table </li></ul...
Dictionary<TKey,TValue>  Class (2) <ul><ul><li>Object.GetHashCode()  method for calculating the hash codes of the elements...
Dictionary<TKey,TValue>  Class (3) <ul><ul><li>Count  – returns the number of elements </li></ul></ul><ul><ul><li>Contains...
Dictionary<TKey,Tvalue>  –  Example Dictionary<string, int> studentsMarks    = new Dictionary<string, int>(); studentsMark...
Counting Words in Given Text string text = &quot;Welcome to our C# course. In this &quot; + &quot;course you will learn ho...
Balanced Trees in .NET <ul><li>Balanced Binary Search Trees </li></ul><ul><ul><li>Ordered binary search trees that have he...
Sorted Dictionary – Example  string text = &quot;Welcome to our C# course. In this &quot; + &quot;course you will learn ho...
Attributes What They Are? How and When to Use Them?
What Are Attributes? <ul><li>Special declarative tags for attaching descriptive information  ( annotations )  to the decla...
Attributes Applying – Example <ul><li>Attribute's name is surrounded by square brackets and is placed before the declarati...
Attributes With Parameters <ul><li>Attributes use parameters for initialization: </li></ul><ul><li>In the example the  [ D...
C# Language Overview (Part II) <ul><li>Questions? </li></ul>http://academy.telerik.com
Upcoming SlideShare
Loading in …5
×

C# Language Overview Part II

2,717 views

Published on

Published in: Technology
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,717
On SlideShare
0
From Embeds
0
Number of Embeds
10
Actions
Shares
0
Downloads
668
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide
  • * 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.* ##
  • * 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.* ##
  • * 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.* ##
  • * (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.* ## 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 .
  • * (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# Language Overview Part II

    1. 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. 2. Table of Contents <ul><li>Creating and Using Objects </li></ul><ul><li>Exceptions Handling </li></ul><ul><li>Strings and Text Processing </li></ul><ul><li>Generics </li></ul><ul><li>Collection Classes </li></ul><ul><li>Attributes </li></ul>
    3. 3. Using Classes and Objects Using the Standard .NET Framework Classes
    4. 4. What is Class? <ul><li>The formal definition of class : </li></ul><ul><li>Definition by Google </li></ul>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. 5. Classes <ul><li>Classes provide the structure for objects </li></ul><ul><ul><li>Define their prototype, act as template </li></ul></ul><ul><li>Classes define: </li></ul><ul><ul><li>Set of attributes </li></ul></ul><ul><ul><ul><li>Represented by fields and properties </li></ul></ul></ul><ul><ul><ul><li>Hold their state </li></ul></ul></ul><ul><ul><li>Set of actions ( behavior ) </li></ul></ul><ul><ul><ul><li>Represented by methods </li></ul></ul></ul><ul><li>A class defines the methods and types of data associated with an object </li></ul>
    6. 6. Classes – Example Account +Owner: Person +Ammount: double +Suspend() +Deposit(sum:double) +Withdraw(sum:double) Class Name Attributes (Properties and Fields) Operations (Methods)
    7. 7. Objects <ul><li>An object is a concrete instance of a particular class </li></ul><ul><li>Creating an object from a class is called instantiation </li></ul><ul><li>Objects have state </li></ul><ul><ul><li>Set of values associated to their attributes </li></ul></ul><ul><li>Example: </li></ul><ul><ul><li>Class: Account </li></ul></ul><ul><ul><li>Objects: Ivan's account, Peter's account </li></ul></ul>
    8. 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. 9. Classes in C# <ul><li>Basic units that compose programs </li></ul><ul><li>Implementation is encapsulated (hidden) </li></ul><ul><li>Classes in C# can contain: </li></ul><ul><ul><li>Fields (member variables) </li></ul></ul><ul><ul><li>Properties </li></ul></ul><ul><ul><li>Methods </li></ul></ul><ul><ul><li>Constructors </li></ul></ul><ul><ul><li>Inner types </li></ul></ul><ul><ul><li>Etc. (events, indexers, operators, …) </li></ul></ul>
    10. 10. Classes in C# – Examples <ul><li>Example of classes: </li></ul><ul><ul><li>System.Console </li></ul></ul><ul><ul><li>System.String ( string in C#) </li></ul></ul><ul><ul><li>System.Int32 ( int in C#) </li></ul></ul><ul><ul><li>System.Array </li></ul></ul><ul><ul><li>System.Math </li></ul></ul><ul><ul><li>System.Random </li></ul></ul>
    11. 11. Declaring Objects <ul><li>An instance of a class or structure can be defined like any other variable: </li></ul><ul><li>Instances cannot be used if they are not initialized </li></ul>using System; ... // Define two variables of type DateTime DateTime today; DateTime halloween; // Declare and initialize a structure instance DateTime today = DateTime.Now;
    12. 12. Fields <ul><li>Fields are data members of a class </li></ul><ul><li>Can be variables and constants </li></ul><ul><li>Accessing a field doesn’t invoke any actions of the object </li></ul><ul><li>Example: </li></ul><ul><ul><li>String.Empty (the &quot;&quot; string) </li></ul></ul>
    13. 13. Accessing Fields <ul><li>Constant fields can be only read </li></ul><ul><li>Variable fields can be read and modified </li></ul><ul><li>Usually properties are used instead of directly accessing variable fields </li></ul><ul><li>Examples: </li></ul>// Accessing read-only field String empty = String.Empty; // Accessing constant field int maxInt = Int32.MaxValue;
    14. 14. Properties <ul><li>Properties look like fields (have name and type), but they can contain code, executed when they are accessed </li></ul><ul><li>Usually used to control access to data fields (wrappers), but can contain more complex logic </li></ul><ul><li>Can have two components (and at least one of them) called accessors </li></ul><ul><ul><li>get for reading their value </li></ul></ul><ul><ul><li>set for changing their value </li></ul></ul>
    15. 15. Properties (2) <ul><li>According to the implemented accessors properties can be: </li></ul><ul><ul><li>Read-only ( get accessor only) </li></ul></ul><ul><ul><li>Read and write (both get and set accessors) </li></ul></ul><ul><ul><li>Write-only ( set accessor only) </li></ul></ul><ul><li>Example of read-only property: </li></ul><ul><ul><li>String.Length </li></ul></ul>
    16. 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. 17. Instance and Static Members <ul><li>Fields, properties and methods can be: </li></ul><ul><ul><li>Instance (or object members) </li></ul></ul><ul><ul><li>Static (or class members) </li></ul></ul><ul><li>Instance members are specific for each object </li></ul><ul><ul><li>Example: different dogs have different name </li></ul></ul><ul><li>Static members are common for all instances of a class </li></ul><ul><ul><li>Example: DateTime.MinValue is shared between all instances of DateTime </li></ul></ul>
    18. 18. Instance and Static Members – Examples <ul><li>Example of instance member </li></ul><ul><ul><li>String.Length </li></ul></ul><ul><ul><ul><li>Each string object has different length </li></ul></ul></ul><ul><li>Example of static member </li></ul><ul><ul><li>Console.ReadLine() </li></ul></ul><ul><ul><ul><li>The console is only one (global for the program) </li></ul></ul></ul><ul><ul><ul><li>Reading from the console does not require to create an instance of it </li></ul></ul></ul>
    19. 19. Methods <ul><li>Methods manipulate the data of the object to which they belong or perform other tasks </li></ul><ul><li>Examples: </li></ul><ul><ul><li>Console.WriteLine(…) </li></ul></ul><ul><ul><li>Console.ReadLine() </li></ul></ul><ul><ul><li>String.Substring(index, length) </li></ul></ul><ul><ul><li>Array.GetLength(index) </li></ul></ul>
    20. 20. Instance Methods <ul><li>Instance methods manipulate the data of a specified object or perform any other tasks </li></ul><ul><ul><li>If a value is returned, it depends on the particular class instance </li></ul></ul><ul><li>Syntax: </li></ul><ul><ul><li>The name of the instance, followed by the name of the method, separated by dot </li></ul></ul><object_name>.<method_name>(<parameters>)
    21. 21. Calling Instance Methods – Examples <ul><li>Calling instance methods of String : </li></ul><ul><li>Calling instance methods of DateTime : </li></ul>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. 22. Static Methods <ul><li>Static methods are common for all instances of a class (shared between all instances) </li></ul><ul><ul><li>Returned value depends only on the passed parameters </li></ul></ul><ul><ul><li>No particular class instance is available </li></ul></ul><ul><li>Syntax: </li></ul><ul><ul><li>The name of the class, followed by the name of the method, separated by dot </li></ul></ul><class_name>.<method_name>(<parameters>)
    23. 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. 24. Constructors <ul><li>Constructors are special methods used to assign initial values of the fields in an object </li></ul><ul><ul><li>Executed when an object of a given type is being created </li></ul></ul><ul><ul><li>Have the same name as the class that holds them </li></ul></ul><ul><ul><li>Do not return a value </li></ul></ul><ul><li>A class may have several constructors with different set of parameters </li></ul>
    25. 25. Constructors (2) <ul><li>Constructor is invoked by the new operator </li></ul><ul><li>Examples: </li></ul>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. 26. Structures <ul><li>Structures are similar to classes </li></ul><ul><li>Structures are usually used for storing data structures, without any other functionality </li></ul><ul><li>Structures can have fields, properties, etc. </li></ul><ul><ul><li>Using methods is not recommended </li></ul></ul><ul><li>Structures are value types , and classes are reference types (this will be discussed later) </li></ul><ul><li>Example of structure </li></ul><ul><ul><li>System.DateTime – represents a date and time </li></ul></ul>
    27. 27. What is a Namespace? <ul><li>Namespaces are used to organize the source code into more logical and manageable way </li></ul><ul><li>Namespaces can contain </li></ul><ul><ul><li>Definitions of classes, structures, interfaces and other types and other namespaces </li></ul></ul><ul><li>Namespaces can contain other namespaces </li></ul><ul><li>For example: </li></ul><ul><ul><li>System namespace contains Data namespace </li></ul></ul><ul><ul><li>The name of the nested namespace is System.Data </li></ul></ul>
    28. 28. Full Class Names <ul><li>A full name of a class is the name of the class preceded by the name of its namespace </li></ul><ul><li>Example: </li></ul><ul><ul><li>Array class, defined in the System namespace </li></ul></ul><ul><ul><li>The full name of the class is System.Array </li></ul></ul><namespace_name>.<class_name>
    29. 29. Including Namespaces <ul><li>The using directive in C#: </li></ul><ul><li>Allows using types in a namespace, without specifying their full name </li></ul><ul><li>Example: </li></ul><ul><li>instead of </li></ul>using <namespace_name> using System; DateTime date; System.DateTime date;
    30. 30. Common Type System (CTS) <ul><li>CTS defines all data types supported in .NET Framework </li></ul><ul><ul><li>Primitive types (e.g. int , float , object ) </li></ul></ul><ul><ul><li>Classes (e.g. String , Console , Array ) </li></ul></ul><ul><ul><li>Structures (e.g. DateTime ) </li></ul></ul><ul><ul><li>Arrays (e.g. int [] , string[,] ) </li></ul></ul><ul><ul><li>Etc. </li></ul></ul><ul><li>Object-oriented by design </li></ul>
    31. 31. CTS and Different Languages <ul><li>CTS is common for all .NET languages </li></ul><ul><ul><li>C#, VB.NET, J#, JScript.NET , ... </li></ul></ul><ul><li>CTS type mappings: </li></ul>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. 32. Value and Reference Types <ul><li>In CTS there are two categories of types </li></ul><ul><ul><li>Value types </li></ul></ul><ul><ul><li>Reference types </li></ul></ul><ul><li>Placed in different areas of memory </li></ul><ul><ul><li>Value types live in the execution stack </li></ul></ul><ul><ul><ul><li>Freed when become out of scope </li></ul></ul></ul><ul><ul><li>Reference types live in the managed heap (dynamic memory) </li></ul></ul><ul><ul><ul><li>Freed by the garbage collector </li></ul></ul></ul>
    33. 33. Value and Reference Types – Examples <ul><li>Value types </li></ul><ul><ul><li>Most of the primitive types </li></ul></ul><ul><ul><li>Structures </li></ul></ul><ul><ul><li>Examples: int , float , bool , DateTime </li></ul></ul><ul><li>Reference types </li></ul><ul><ul><li>Classes and interfaces </li></ul></ul><ul><ul><li>Strings </li></ul></ul><ul><ul><li>Arrays </li></ul></ul><ul><ul><li>Examples: string , Random , object , int[] </li></ul></ul>
    34. 34. Exceptions Handling The Paradigm of Exceptions in OOP
    35. 35. What are Exceptions? <ul><li>The exceptions in .NET Framework are classic implementation of the OOP exception model </li></ul><ul><li>Deliver powerful mechanism for centralized handling of errors and unusual events </li></ul><ul><li>Substitute procedure-oriented approach, in which each function returns error code </li></ul><ul><li>Simplify code construction and maintenance </li></ul><ul><li>Allow the problematic situations to be processed at multiple levels </li></ul>
    36. 36. Handling Exceptions <ul><li>In C# the exceptions can be handled by the try-catch-finally construction </li></ul><ul><li>catch blocks can be used multiple times to process different exception types </li></ul>try { // Do some work that can raise an exception } catch (SomeException) { // Handle the caught exception }
    37. 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. 38. The System.Exception Class <ul><li>Exceptions in .NET are objects </li></ul><ul><li>The System.Exception class is base for all exceptions in CLR </li></ul><ul><ul><li>Contains information for the cause of the error or the unusual situation </li></ul></ul><ul><ul><ul><li>Message – text description of the exception </li></ul></ul></ul><ul><ul><ul><li>StackTrace – the snapshot of the stack at the moment of exception throwing </li></ul></ul></ul><ul><ul><ul><li>InnerException – exception caused the current exception ( if any ) </li></ul></ul></ul>
    39. 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. 40. Exception Properties <ul><li>The Message property gives brief description of the problem </li></ul><ul><li>The StackTrace property is extremely useful when identifying the reason caused the exception </li></ul>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
    41. 41. Exception Properties (2) <ul><li>File names and line numbers are accessible only if the compilation was in Debug mode </li></ul><ul><li>When compiled in Release mode, the information in the property StackTrace is quite different: </li></ul>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. 42. Exception Hierarchy <ul><li>Exceptions in .NET Framework are organized in a hierarchy </li></ul>
    43. 43. Types of Exceptions <ul><li>All .NET exceptions inherit from System.Exception </li></ul><ul><li>The system exceptions inherit from System.SystemException , e.g. </li></ul><ul><ul><li>System.ArgumentException </li></ul></ul><ul><ul><li>System.NullReferenceException </li></ul></ul><ul><ul><li>System.OutOfMemoryException </li></ul></ul><ul><ul><li>System.StackOverflowException </li></ul></ul><ul><li>User-defined exceptions should inherit from System.ApplicationException </li></ul>
    44. 44. Handling Exceptions <ul><li>When catching an exception of a particular class, all its inheritors (child exceptions) are caught too </li></ul><ul><li>Example: </li></ul><ul><li>Handles ArithmeticException and its successors DivideByZeroException and OverflowException </li></ul>try { // Do some works that can raise an exception } catch (System.ArithmeticException) { // Handle the caught arithmetic exception }
    45. 45. Handling All Exceptions <ul><li>All exceptions thrown by .NET managed code inherit the System.Exception exception </li></ul><ul><li>Unmanaged code can throw other exceptions </li></ul><ul><li>For handling all exceptions (even unmanaged) use the construction: </li></ul>try { // Do some works that can raise any exception } catch { // Handle the caught exception }
    46. 46. Throwing Exceptions <ul><li>Exceptions are thrown (raised) by throw keyword in C# </li></ul><ul><ul><li>Used to notify the calling code in case of error or unusual situation </li></ul></ul><ul><li>When an exception is thrown: </li></ul><ul><ul><li>The program execution stops </li></ul></ul><ul><ul><li>The exception travels over the stack until a suitable catch block is reached to handle it </li></ul></ul><ul><li>Unhandled exceptions display error message </li></ul>
    47. 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. 48. Using throw Keyword <ul><li>Throwing an exception with error message: </li></ul><ul><li>Exceptions can take message and cause: </li></ul><ul><li>Note : if the original exception is not passed the initial cause of the exception is lost </li></ul>throw new ArgumentException(&quot;Invalid amount!&quot;); try { Int32.Parse(str); } catch (FormatException fe) { throw new ArgumentException(&quot;Invalid number&quot;, fe); }
    49. 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. 50. Strings and Text Processing
    51. 51. What Is String? <ul><li>Strings are sequences of characters </li></ul><ul><li>Each character is a Unicode symbol </li></ul><ul><li>Represented by the string data type in C# ( System.String ) </li></ul><ul><li>Example: </li></ul>string s = &quot;Hello, C#&quot;; s H e l l o , C #
    52. 52. The System.String Class <ul><li>Strings are represented by System.String objects in .NET Framework </li></ul><ul><ul><li>String objects contain an immutable (read-only) sequence of characters </li></ul></ul><ul><ul><li>Strings use Unicode in to support multiple languages and alphabets </li></ul></ul><ul><li>Strings are stored in the dynamic memory ( managed heap ) </li></ul><ul><li>System.String is reference type </li></ul>
    53. 53. The System.String Class (2) <ul><li>String objects are like arrays of characters ( char[] ) </li></ul><ul><ul><li>Have fixed length ( String.Length ) </li></ul></ul><ul><ul><li>Elements can be accessed directly by index </li></ul></ul><ul><ul><ul><li>The index is in the range [ 0 ... Length-1 ] </li></ul></ul></ul>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. 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. 55. Declaring Strings <ul><li>There are two ways of declaring string variables: </li></ul><ul><ul><li>Using the C# keyword string </li></ul></ul><ul><ul><li>Using the .NET's fully qualified class name System.String </li></ul></ul><ul><ul><li>The above three declarations are equivalent </li></ul></ul>string str1; System.String str2; String str3;
    56. 56. Creating Strings <ul><li>Before initializing a string variable has null value </li></ul><ul><li>Strings can be initialized by: </li></ul><ul><ul><li>Assigning a string literal to the string variable </li></ul></ul><ul><ul><li>Assigning the value of another string variable </li></ul></ul><ul><ul><li>Assigning the result of operation of type string </li></ul></ul>
    57. 57. Creating Strings (2) <ul><li>Not initialized variables has value of null </li></ul><ul><li>Assigning a string literal </li></ul><ul><li>Assigning from another string variable </li></ul><ul><li>Assigning from the result of string operation </li></ul>string s; // s is equal to null string s = &quot;I am a string literal!&quot;; string s2 = s; string s = 42.ToString();
    58. 58. Reading and Printing Strings <ul><li>Reading strings from the console </li></ul><ul><ul><li>Use the method Console. ReadLine() </li></ul></ul>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;); <ul><li>Printing strings to the console </li></ul><ul><ul><li>Use the methods Write() and WriteLine() </li></ul></ul>
    59. 59. Comparing Strings <ul><li>A number of ways exist to compare two strings: </li></ul><ul><ul><li>Dictionary-based string comparison </li></ul></ul><ul><ul><ul><li>Case-insensitive </li></ul></ul></ul><ul><ul><ul><li>Case-sensitive </li></ul></ul></ul>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. 60. Comparing Strings – Example <ul><li>Finding the first string in a lexicographical order from a given list of strings: </li></ul>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. 61. Concatenating Strings <ul><li>There are two ways to combine strings: </li></ul><ul><ul><li>Using the Concat() method </li></ul></ul><ul><ul><li>Using the + or the += operators </li></ul></ul><ul><li>Any object can be appended to string </li></ul>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. 62. Searching in Strings <ul><li>Finding a character or substring within given string </li></ul><ul><ul><li>First occurrence </li></ul></ul><ul><ul><li>First occurrence starting at given position </li></ul></ul><ul><ul><li>Last occurrence </li></ul></ul>IndexOf(string str) IndexOf(string str, int startIndex) LastIndexOf(string)
    63. 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. 64. Extracting Substrings <ul><li>Extracting substrings </li></ul><ul><ul><li>str.Substring(int startIndex, int length) </li></ul></ul><ul><ul><li>str.Substring(int startIndex) </li></ul></ul>string filename = @&quot;C:PicsRila2009.jpg&quot;; string name = filename.Substring(8, 8); // name is Rila2009 string filename = @&quot;C:PicsSummer2009.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. 65. Splitting Strings <ul><li>To split a string by given separator(s) use the following method: </li></ul><ul><li>Example: </li></ul>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. 66. Replacing and Deleting Substrings <ul><li>Replace(string, string) – replaces all occurrences of given string with another </li></ul><ul><ul><li>The result is new string (strings are immutable) </li></ul></ul><ul><li>Re move ( index , length ) – deletes part of a string and produces new string as result </li></ul>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. 67. Changing Character Casing <ul><li>Using method ToLower() </li></ul><ul><li>Using method ToUpper() </li></ul>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. 68. Trimming White Space <ul><li>Using method Trim() </li></ul><ul><li>Using method Trim(chars ) </li></ul><ul><li>Using Trim Start () and Trim End () </li></ul>string s = &quot; example of white space &quot;; string clean = s.Trim(); Console.WriteLine(clean); string s = &quot; tnHello!!! 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. 69. Constructing Strings <ul><li>Strings are immutable </li></ul><ul><ul><li>C oncat() , R eplace() , T rim() , ... return new string, do not modify the old one </li></ul></ul><ul><li>Do not use &quot; + &quot; for strings in a loop! </li></ul><ul><ul><li>It runs very, very inefficiently! </li></ul></ul>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. 70. Changing the Contents of a String – StringBuilder <ul><li>Use the System.Text.StringBuilder class for modifiable strings of characters: </li></ul><ul><li>Use StringBuilder if you need to keep adding characters to a string </li></ul>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. 71. The StringBuilde r Class <ul><li>StringBuilder keeps a buffer memory, allocated in advance </li></ul><ul><ul><li>Most operations use the buffer memory and do not allocate new objects </li></ul></ul><ul><li>StringBuilder : </li></ul><ul><ul><li>Length =9 </li></ul></ul><ul><ul><li>Capacity =15 </li></ul></ul>Capacity used buffer ( Length ) unused buffer H e l l o , C # !
    72. 72. StringBuilder – Example <ul><li>Extracting all capital letters from a string </li></ul>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. 73. Method ToString() <ul><li>All classes have public virtual method ToString() </li></ul><ul><ul><li>Returns a human-readable, culture-sensitive string representing the object </li></ul></ul><ul><ul><li>Most .NET Framework types have own implementation of ToString() </li></ul></ul><ul><ul><ul><li>int , float , bool , DateTime </li></ul></ul></ul>int number = 5; string s = &quot;The number is &quot; + number.ToString(); Console.WriteLine(s); // The number is 5
    74. 74. Method ToString(format ) <ul><li>We can apply specific formatting when converting objects to string </li></ul><ul><ul><li>ToString(fo r matString) method </li></ul></ul>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. 75. Formatting Strings <ul><li>The formatting strings are different for the different types </li></ul><ul><li>Some formatting strings for numbers: </li></ul><ul><ul><li>D – number (for integer types) </li></ul></ul><ul><ul><li>C – currency (according to current culture) </li></ul></ul><ul><ul><li>E – number in exponential notation </li></ul></ul><ul><ul><li>P – percentage </li></ul></ul><ul><ul><li>X – hexadecimal number </li></ul></ul><ul><ul><li>F – fixed point (for real numbers) </li></ul></ul>
    76. 76. Method String.Format() <ul><li>Applies templates for formatting strings </li></ul><ul><ul><li>Placeholders are used for dynamic text </li></ul></ul><ul><ul><li>Like Console.WriteLine(…) </li></ul></ul>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. 77. Composite Formatting <ul><li>The placeholders in the composite formatting strings are specified as follows: </li></ul><ul><li>Examples: </li></ul>{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. 78. Formatting Dates <ul><li>Dates have their own formatting strings </li></ul><ul><ul><li>d , dd – day (with/without leading zero) </li></ul></ul><ul><ul><li>M , MM – month </li></ul></ul><ul><ul><li>yy , yyyy – year (2 or 4 digits) </li></ul></ul><ul><ul><li>h , HH , m , mm , s , ss – hour, minute, second </li></ul></ul>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. 79. Collection Classes Lists, Trees, Dictionaries
    80. 80. What are Generics? <ul><li>Generics allow defining parameterized classes that process data of unknown (generic) type </li></ul><ul><ul><li>The class can be instantiated with several different particular types </li></ul></ul><ul><ul><li>Example: List<T>  List<int> / List<string> / List<Student> </li></ul></ul><ul><li>Generics are also known as &quot; parameterized types &quot; or &quot; template types &quot; </li></ul><ul><ul><li>Similar to the templates in C++ </li></ul></ul><ul><ul><li>Similar to the generics in Java </li></ul></ul>
    81. 81. The List<T> Class <ul><li>Implements the abstract data structure list using an array </li></ul><ul><ul><li>All elements are of the same type T </li></ul></ul><ul><ul><li>T can be any type, e.g. List<int> , List<string> , List<DateTime> </li></ul></ul><ul><ul><li>Size is dynamically increased as needed </li></ul></ul><ul><li>Basic functionality: </li></ul><ul><ul><li>Count – returns the number of elements </li></ul></ul><ul><ul><li>Add(T) – appends given element at the end </li></ul></ul>
    82. 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. 83. List<T> – Functionality <ul><li>list[index] – access element by index </li></ul><ul><li>Insert(index , T) – inserts given element to the list at a specified position </li></ul><ul><li>Remove(T) – removes the first occurrence of given element </li></ul><ul><li>RemoveAt(index) – removes the element at the specified position </li></ul><ul><li>Clear() – removes all elements </li></ul><ul><li>Contains(T ) – determines whether an element is part of the list </li></ul>
    84. 84. List<T> – Functionality (2) <ul><li>IndexOf() – returns the index of the first occurrence of a value in the list ( zero-based ) </li></ul><ul><li>Reverse() – reverses the order of the elements in the list or a portion of it </li></ul><ul><li>Sort() – sorts the elements in the list or a portion of it </li></ul><ul><li>ToArray() – converts the elements of the list to an array </li></ul><ul><li>TrimExcess() – sets the capacity to the actual number of elements </li></ul>
    85. 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. 86. The Stack<T> Class <ul><li>Implements the stack data structure using an array </li></ul><ul><ul><li>Elements are of the same type T </li></ul></ul><ul><ul><li>T can be any type, e.g. Stack<int> </li></ul></ul><ul><ul><li>Size is dynamically increased as needed </li></ul></ul><ul><li>Basic functionality: </li></ul><ul><ul><li>Push(T) – inserts elements to the stack </li></ul></ul><ul><ul><li>Pop() – removes and returns the top element from the stack </li></ul></ul>
    87. 87. Stack<T> – Example <ul><li>Using Push() , Pop() and Peek() methods </li></ul>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. 88. The Queue<T> Class <ul><li>Implements the queue data structure using a circular resizable array </li></ul><ul><ul><li>Elements are from the same type T </li></ul></ul><ul><ul><li>T can be any type, e.g. Stack<int> </li></ul></ul><ul><ul><li>Size is dynamically increased as needed </li></ul></ul><ul><li>Basic functionality: </li></ul><ul><ul><li>Enqueue(T) – adds an element to the end of the queue </li></ul></ul><ul><ul><li>Dequeue() – removes and returns the element at the beginning of the queue </li></ul></ul>
    89. 89. Queue<T> – Example <ul><li>Using Enqueue() and Dequeue() methods </li></ul>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. 90. Dictionary<TKey,TValue> Class <ul><li>Implements the abstract data type &quot; Dictionary &quot; as hash table </li></ul><ul><ul><li>Size is dynamically increased as needed </li></ul></ul><ul><ul><li>Contains a collection of key-and-value pairs arranged by the hash code of the key – h(key) = value </li></ul></ul><ul><ul><li>Collisions are resolved by chaining </li></ul></ul><ul><li>Dictionary<TKey,TValue> class relies on </li></ul><ul><ul><li>Object. Equals( ) method for comparing elements </li></ul></ul>
    91. 91. Dictionary<TKey,TValue> Class (2) <ul><ul><li>Object.GetHashCode() method for calculating the hash codes of the elements </li></ul></ul><ul><li>Major operations: </li></ul><ul><ul><li>Add(TKey,TValue) – adds an element with the specified key and value into the dictionary </li></ul></ul><ul><ul><li>Remove(TKey) – removes the element with the specified key </li></ul></ul><ul><ul><li>Clear() – removes all elements </li></ul></ul><ul><ul><li>this[] – returns element by key </li></ul></ul>
    92. 92. Dictionary<TKey,TValue> Class (3) <ul><ul><li>Count – returns the number of elements </li></ul></ul><ul><ul><li>ContainsKey(TKey) – determines whether the dictionary contains given key </li></ul></ul><ul><ul><li>ContainsValue(TValue) – determines whether the dictionary contains given value </li></ul></ul><ul><ul><li>Keys – returns a collection of the keys </li></ul></ul><ul><ul><li>Values – returns a collection of the values </li></ul></ul><ul><ul><li>TryGetValue(TKey,out TValue ) – if the key is found, returns it in the TValue , otherwise returns the default value for the TValue type </li></ul></ul>
    93. 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. 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. 95. Balanced Trees in .NET <ul><li>Balanced Binary Search Trees </li></ul><ul><ul><li>Ordered binary search trees that have height of log 2 (n) where n is the number of their nodes </li></ul></ul><ul><ul><li>Searching costs about log 2 (n) comparisons </li></ul></ul><ul><li>.NET Framework has built-in implementations of balanced search trees, e.g.: </li></ul><ul><ul><li>SortedDictionary<K,V> </li></ul></ul><ul><ul><ul><li>Red-black tree based map of key-value pairs </li></ul></ul></ul><ul><li>External libraries like &quot;Wintellect Power Collections for .NET&quot; are more flexible </li></ul>
    96. 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. 97. Attributes What They Are? How and When to Use Them?
    98. 98. What Are Attributes? <ul><li>Special declarative tags for attaching descriptive information ( annotations ) to the declarations in the code </li></ul><ul><li>At compile time attributes are saved in the assembly's metadata </li></ul><ul><li>Can be extracted from the metadata and can be manipulated by different tools </li></ul><ul><li>Instances of classes derived from System.Attribute </li></ul>
    99. 99. Attributes Applying – Example <ul><li>Attribute's name is surrounded by square brackets and is placed before the declaration which it refers to: </li></ul><ul><li>[Flags] attribute indicates that the enum type can be treated like a set of bit flags </li></ul>[Flags] // System.FlagsAttribute public enum FileAccess { Read = 1, Write = 2, ReadWrite = Read | Write }
    100. 100. Attributes With Parameters <ul><li>Attributes use parameters for initialization: </li></ul><ul><li>In the example the [ DllImport ] attribute is instantiated by the compiler as follows : </li></ul><ul><ul><li>An object of System.Runtime. InteropServices.DllImportAttribute class is created and initialized </li></ul></ul>[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. 101. C# Language Overview (Part II) <ul><li>Questions? </li></ul>http://academy.telerik.com

    ×