0
C# Language Overview (Part II)      Creating and Using Objects, Exceptions, Strings,                      Generics, Collec...
Table of Contents1.   Creating and Using Objects2.   Exceptions Handling3.   Strings and Text Processing4.   Generics5.   ...
Using Classes and ObjectsUsing the Standard .NET Framework Classes
What is Class? The formal definition of class:   Classes act as templates from which an   instance of an object is create...
Classes Classes   provide the structure for objects   Define their prototype, act as template Classes define:   Set of...
Classes – Example          Class Name     Attributes                        (Properties       Account          and Fields)...
Objects An object is a concrete instance of a particular class Creating an object from a class is called instantiation ...
Objects – Example                                               Object             Class          ivanAccount             ...
Classes in C# Basic units   that compose programs Implementation is encapsulated     (hidden) Classes   in C# can conta...
Classes in C# – Examples Example of classes:   System.Console   System.String (string in C#)   System.Int32 (int in C#...
Declaring Objects An instance of a class                       or structure can be defined like any other variable:  usin...
Fields Fields are data members of a class Can be variables   and constants Accessing a field doesn’t invoke any actions...
Accessing Fields Constant fields can be only read Variable   fields can be read and modified Usually properties are use...
Properties Properties look like fields (have name and type), but they can contain code, executed when they are accessed ...
Properties (2) According to the implemented accessors properties can be:  Read-only (get accessor only)  Read and write...
Accessing Properties and Fields –                                  Exampleusing System;...DateTime christmas = new DateTim...
Instance and Static Members Fields, properties   and methods can be:   Instance (or object members)   Static (or class ...
Instance and Static                          Members – Examples   Example of instance member     String.Length      Eac...
Methods Methods manipulate the data of the object to which they belong or perform other tasks Examples:   Console.Write...
Instance Methods Instance methods manipulate  the data of a specified object or perform any other tasks  If a value is r...
Calling Instance Methods –                                     Examples Calling   instance methods of String:   String sa...
Static Methods Static methods are common for all instances of a class (shared between all instances)   Returned value de...
Calling Static Methods – Examples                     Constant      Staticusing System;                       field      m...
Constructors Constructors are  special methods used to assign initial values of the fields in an object   Executed when ...
Constructors (2) Constructor is invoked by the new operator  <instance_name> = new <class_name>(<parameters>) Examples: ...
Structures Structures are similar   to classes Structures are usually                       used for storing data struct...
What is a Namespace? Namespaces are used to organize the source code into more logical and manageable way Namespaces can...
Full Class Names A full name of a class is the name of the class preceded by the name of its namespace  <namespace_name>....
Including Namespaces The using directive in C#:  using <namespace_name> Allows using types  in a namespace, without spec...
Common Type System (CTS) CTS defines all   data types supported in .NET Framework   Primitive types (e.g. int, float, ob...
CTS and Different Languages CTS is common for all .NET languages  C#, VB.NET, J#, JScript.NET, ... CTS type mappings:  ...
Value and Reference Types In CTS there are two categories of types   Value types   Reference types Placed in different...
Value and Reference Types –                              Examples Value types  Most of the primitive types  Structures ...
Exceptions HandlingThe Paradigm of Exceptions in OOP
What are Exceptions? The exceptions in .NET Framework are classic implementation of the OOP exception model Deliver powe...
Handling Exceptions In C# the exceptions can be handled by the try-catch-finally construction  try  {        // Do some w...
Handling Exceptions – Examplestatic void Main(){    string s = Console.ReadLine();    try    {        Int32.Parse(s);     ...
The System.Exception Class Exceptions in .NET are objects The System.Exception class is base for all exceptions in CLR  ...
Exception Properties – Exampleclass ExceptionsTest{   public static void CauseFormatException()   {       string s = "an i...
Exception Properties   The Message property gives brief description of the    problem   The StackTrace property is extre...
Exception Properties (2)   File names and line numbers are accessible only if the    compilation was in Debug mode   Whe...
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.S...
Handling Exceptions   When catching an exception of a particular class, all    its inheritors (child exceptions) are caug...
Handling All Exceptions   All exceptions thrown by .NET managed code    inherit the System.Exception exception   Unmanag...
Throwing Exceptions Exceptions are thrown    (raised) by throw keyword in C#  Used to notify the calling code in case of...
How Exceptions Work?           5. Throw an exceptionMethod N                           Method N   …          4. Method cal...
Using throw Keyword   Throwing an exception with error message:     throw new ArgumentException("Invalid amount!");   Ex...
Throwing Exceptions – Examplepublic static double Sqrt(double value){    if (value < 0)        throw new System.ArgumentOu...
Strings and Text Processing
What Is String? Strings are sequences of characters Each character is a Unicode symbol Represented by the string data  ...
The System.String Class Strings are represented by                          System.String objects in .NET Framework   St...
The System.String Class (2)   String objects are like arrays of characters    (char[])     Have fixed length (String.Len...
Strings – Examplestatic void Main(){    string s =        "Stand up, stand up, Balkan Superman.";    Console.WriteLine("s ...
Declaring Strings There are two ways      of declaring string variables:  Using the C# keyword string  Using the .NETs ...
Creating Strings Before initializing   a string variable has null value Strings can be initialized   by:   Assigning a ...
Creating Strings (2)   Not initialized variables has value of null     string s; // s is equal to null   Assigning a str...
Reading and Printing Strings Reading strings    from the console   Use the method Console.ReadLine()  string s = Console...
Comparing Strings A number of ways      exist to compare two strings:  Dictionary-based string comparison    Case-insen...
Comparing Strings – Example   Finding the first string in a lexicographical order    from a given list of strings:    str...
Concatenating Strings   There are two ways to combine strings:     Using the Concat() method     string str = String.Con...
Searching in Strings   Finding a character or substring within given    string     First occurrence     IndexOf(string s...
Searching in Strings – Example  string str = "C# Programming Course";  int index = str.IndexOf("C#"); // index = 0  index ...
Extracting Substrings Extracting substrings      str.Substring(int startIndex, int length)     string filename = @"C:Pic...
Splitting Strings   To split a string by given separator(s) use the    following method:      string[] Split(params char[...
Replacing and Deleting Substrings   Replace(string, string) – replaces all    occurrences of given string with another   ...
Changing Character Casing   Using method ToLower()     string alpha = "aBcDeFg";     string lowerAlpha = alpha.ToLower();...
Trimming White Space   Using method Trim()     string s = "    example of white space   ";     string clean = s.Trim();  ...
Constructing Strings Strings are immutable   Concat(), Replace(), Trim(), ... return new    string, do not modify the ol...
Changing the Contents of a String                            – StringBuilder   Use the System.Text.StringBuilder class fo...
The StringBuilder Class                           CapacityStringBuilder: H e l l o , C # !  Length=9  Capacity=15       us...
StringBuilder – Example Extracting all capital   letters from a string   public static string ExtractCapitals(string s)  ...
Method ToString() All classes         have public virtual method ToString()   Returns a human-readable, culture-sensitiv...
Method ToString(format) We can applyspecific formatting when converting objects to string   ToString(formatString) metho...
Formatting Strings   The formatting strings are different for the    different types   Some formatting strings for numbe...
Method String.Format() Applies templates for formatting strings   Placeholders are used for dynamic text   Like Console...
Composite Formatting   The placeholders in the composite formatting    strings are specified as follows:     {index[,alig...
Formatting Dates Dates have their    own formatting strings   d, dd – day (with/without leading zero)   M, MM – month  ...
Collection Classes  Lists, Trees, Dictionaries
What are Generics? Generics allowdefining parameterized classes that process data of unknown (generic) type   The class ...
The List<T> Class Implements the abstract   data structure list using an array   All elements are of the same type T   ...
List<T> – Simple Examplestatic void Main(){   List<string> list = new List<string>();    list.Add("C#");    list.Add("Java...
List<T> – Functionality   list[index] – access element by index   Insert(index, T) – inserts given element to the    lis...
List<T> – Functionality (2)   IndexOf() – returns the index of the first    occurrence of a value in the list (zero-based...
Primes in an Interval – Examplestatic List<int> FindPrimes(int start, int end){   List<int> primesList = new List<int>(); ...
The Stack<T> Class Implements the stack   data structure using an array   Elements are of the same type T   T can be an...
Stack<T> – Example   Using Push(), Pop() and Peek() methods    static void Main()    {        Stack<string> stack = new S...
The Queue<T> Class Implements the queue data structure using   a circular resizable array   Elements are from the same t...
Queue<T> – Example   Using Enqueue() and Dequeue() methods    static void Main()    {        Queue<string> queue = new Qu...
Dictionary<TKey,TValue> Class Implements the abstract data type "Dictionary" as hash table   Size is dynamically increas...
Dictionary<TKey,TValue> Class                                   (2)   Object.GetHashCode() method for    calculating the ...
Dictionary<TKey,TValue> Class                                   (3) Count – returns the number of elements ContainsKey(T...
Dictionary<TKey,Tvalue> –                                 ExampleDictionary<string, int> studentsMarks   = new Dictionary<...
Counting Words in Given Textstring text = "Welcome to our C# course. In this " + "course you will learn how to write simpl...
Balanced Trees in .NET Balanced Binary Search Trees   Ordered binary search trees that have height of    log2(n) where n...
Sorted Dictionary – Examplestring text = "Welcome to our C# course. In this " + "course you will learn how to write simple...
AttributesWhat They Are? How and When to Use Them?
What Are Attributes? Special declarativetags for attaching descriptive information (annotations) to the declarations in t...
Attributes Applying – Example Attributes name is surrounded by square brackets and is placed before the declaration which...
Attributes With Parameters   Attributes use parameters for initialization:    [DllImport("user32.dll", EntryPoint="Messag...
CSharp Language Overview    курсове и уроци по програмиране, уеб дизайн – безплатно     BG Coder - онлайн състезателна сис...
Free Trainings @ Telerik Academy "C# and Databases       " course @ Telerik    Academy       academy.telerik.com/…csharp...
Upcoming SlideShare
Loading in...5
×

3. C# Language - Overview - Part 2 - C# and Databases

2,985

Published on

C# Language Overview (Part II) - Creating and Using Objects, Exceptions, Strings, Generics, Collections, Attributes
Telerik Software Academy: http://academy.telerik.com/school-academy/meetings/details/2012/01/06/desktop-applications-csharp-databases
The website and all video materials are in Bulgarian.
Creating and Using Objects
Exceptions Handling
Strings and Text Processing
Generics
Collection Classes
Attributes

Published in: Education, Technology
0 Comments
13 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,985
On Slideshare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
583
Comments
0
Likes
13
Embeds 0
No embeds

No notes for slide

Transcript of "3. C# Language - Overview - Part 2 - C# and Databases"

  1. 1. C# Language Overview (Part II) Creating and Using Objects, Exceptions, Strings, Generics, Collections, AttributesDoncho MinkovTechnical Trainerhttp://www.minkov.itTelerik Software Academyhttp://academy.telerik.com/
  2. 2. Table of Contents1. Creating and Using Objects2. Exceptions Handling3. Strings and Text Processing4. Generics5. Collection Classes6. Attributes 2
  3. 3. Using Classes and ObjectsUsing the Standard .NET Framework Classes
  4. 4. What is Class? The formal definition of class: Classes act as templates from which an instance of an object is created at run time. Classes define the properties of the object and the methods used to control the objects behavior. Definition by Google 4
  5. 5. Classes Classes provide the structure for objects  Define their prototype, act as template Classes define:  Set of attributes  Represented by fields and properties  Hold their state  Set of actions (behavior)  Represented by methods A class defines the methods and types of data associated with an object 5
  6. 6. Classes – Example Class Name Attributes (Properties Account and Fields)+Owner: Person+Ammount: double+Suspend() Operations+Deposit(sum:double) (Methods)+Withdraw(sum:double) 6
  7. 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: Ivans account, Peters account 7
  8. 8. Objects – Example Object Class ivanAccount +Owner="Ivan Kolev" Account +Ammount=5000.0+Owner: Person Object+Ammount: double peterAccount+Suspend() +Owner="Peter Kirov"+Deposit(sum:double) +Ammount=1825.33+Withdraw(sum:double) Object kirilAccount +Owner="Kiril Kirov" +Ammount=25.0 8
  9. 9. Classes in C# Basic units that compose programs Implementation is encapsulated (hidden) Classes in C# can contain:  Fields (member variables)  Properties  Methods  Constructors  Inner types  Etc. (events, indexers, operators, …) 9
  10. 10. Classes in C# – Examples Example of classes:  System.Console  System.String (string in C#)  System.Int32 (int in C#)  System.Array  System.Math  System.Random 10
  11. 11. Declaring Objects An instance of a class or structure can be defined like any other variable: using System; ... // Define two variables of type DateTime DateTime today; DateTime halloween; Instances cannot be used if they are not initialized // Declare and initialize a structure instance DateTime today = DateTime.Now; 11
  12. 12. Fields Fields are data members of a class Can be variables and constants Accessing a field doesn’t invoke any actions of the object Example:  String.Empty (the "" string) 12
  13. 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; 13
  14. 14. Properties Properties look like fields (have name and type), but they can contain code, executed when they are accessed Usually used to control access to data fields (wrappers), but can contain more complex logic Can have two components (and at least one of them) called accessors  get for reading their value  set for changing their value 14
  15. 15. Properties (2) According to the implemented accessors properties can be:  Read-only (get accessor only)  Read and write (both get and set accessors)  Write-only (set accessor only) Example of read-only property:  String.Length 15
  16. 16. Accessing Properties and Fields – Exampleusing 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)); 16
  17. 17. Instance and Static Members Fields, properties and methods can be:  Instance (or object members)  Static (or class members) Instance members are specific for each object  Example: different dogs have different name Static members are common for all instances of a class  Example: DateTime.MinValue is shared between all instances of DateTime 17
  18. 18. Instance and Static Members – Examples Example of instance member  String.Length  Each string object has different length Example of static member  Console.ReadLine()  The console is only one (global for the program)  Reading from the console does not require to create an instance of it 18
  19. 19. Methods Methods manipulate the data of the object to which they belong or perform other tasks Examples:  Console.WriteLine(…)  Console.ReadLine()  String.Substring(index, length)  Array.GetLength(index) 19
  20. 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>) 20
  21. 21. Calling Instance Methods – Examples Calling instance methods of String: String sampleLower = new String(a, 5); String sampleUpper = sampleLower.ToUpper(); Console.WriteLine(sampleLower); // aaaaa Console.WriteLine(sampleUpper); // AAAAA Calling instance methods of DateTime: DateTime now = DateTime.Now; DateTime later = now.AddHours(8); Console.WriteLine("Now: {0}", now); Console.WriteLine("8 hours later: {0}", later); 21
  22. 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>) 22
  23. 23. Calling Static Methods – Examples Constant Staticusing System; field methoddouble radius = 2.9;double area = Math.PI * Math.Pow(radius, 2);Console.WriteLine("Area: {0}", area);// Area: 26,4207942166902 Staticdouble precise = 8.7654321; methoddouble round3 = Math.Round(precise, 3);double round1 = Math.Round(precise, 1); StaticConsole.WriteLine( method "{0}; {1}; {2}", precise, round3, round1);// 8,7654321; 8,765; 8,8 23
  24. 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 severalconstructors with different set of parameters 24
  25. 25. Constructors (2) Constructor is invoked by the new operator <instance_name> = new <class_name>(<parameters>) Examples: String s = new String("Hello!"); // s = "Hello!" String s = new String(*, 5); // s = "*****" DateTime dt = new DateTime(2009, 12, 30); DateTime dt = new DateTime(2009, 12, 30, 12, 33, 59); Int32 value = new Int32(1024); 25
  26. 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 valuetypes, and classes are reference types (this will be discussed later) Example of structure  System.DateTime – represents a date and time 26
  27. 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 27
  28. 28. Full Class Names A full name of a class is the name of the class preceded by the name of its namespace <namespace_name>.<class_name> Example:  Array class, defined in the System namespace  The full name of the class is System.Array 28
  29. 29. Including Namespaces The using directive in C#: using <namespace_name> Allows using types in a namespace, without specifying their full name Example: using System; DateTime date; instead of System.DateTime date; 29
  30. 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 30
  31. 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 31
  32. 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 32
  33. 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[] 33
  34. 34. Exceptions HandlingThe Paradigm of Exceptions in OOP
  35. 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 35
  36. 36. Handling Exceptions In C# the exceptions can be handled by the try-catch-finally construction try { // Do some work that can raise an exception } catch (SomeException) { // Handle the caught exception } catch blocks can be used multiple times to process different exception types 36
  37. 37. Handling Exceptions – Examplestatic void Main(){ string s = Console.ReadLine(); try { Int32.Parse(s); Console.WriteLine( "You entered valid Int32 number {0}.", s); } catch (FormatException) { Console.WriteLine("Invalid integer number!"); } catch (OverflowException) { Console.WriteLine( "The number is too big to fit in Int32!"); }} 37
  38. 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) 38
  39. 39. Exception Properties – Exampleclass ExceptionsTest{ public static void CauseFormatException() { string s = "an invalid number"; Int32.Parse(s); } static void Main() { try { CauseFormatException(); } catch (FormatException fe) { Console.Error.WriteLine("Exception caught: {0}n{1}", fe.Message, fe.StackTrace); } }} 39
  40. 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:consoleapplication1exceptionstest.cs:line 8 at ExceptionsTest.Main(String[] args) in c:consoleapplication1exceptionstest.cs:line 15 40
  41. 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) 41
  42. 42. Exception Hierarchy Exceptions in .NET Framework are organized in a hierarchy 42
  43. 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 43
  44. 44. Handling Exceptions When catching an exception of a particular class, all its inheritors (child exceptions) are caught too Example: try { // Do some works that can raise an exception } catch (System.ArithmeticException) { // Handle the caught arithmetic exception } Handles ArithmeticException and its successors DivideByZeroException and OverflowException 44
  45. 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 } 45
  46. 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 46
  47. 47. How Exceptions Work? 5. Throw an exceptionMethod N Method N … 4. Method call … 6. Find handlerMethod 2 Method 2 3. Method call 7. Find handlerMethod 1 Method 1 2. Method call 8. Find handlerMain() Main() .NET CLR 47
  48. 48. Using throw Keyword Throwing an exception with error message: throw new ArgumentException("Invalid amount!"); Exceptions can take message and cause: try { Int32.Parse(str); } catch (FormatException fe) { throw new ArgumentException("Invalid number", fe); } Note: if the original exception is not passed the initial cause of the exception is lost 48
  49. 49. Throwing Exceptions – Examplepublic static double Sqrt(double value){ if (value < 0) throw new System.ArgumentOutOfRangeException( "Sqrt for negative numbers is undefined!"); return Math.Sqrt(value);}static void Main(){ try { Sqrt(-1); } catch (ArgumentOutOfRangeException ex) { Console.Error.WriteLine("Error: " + ex.Message); throw; }} 49
  50. 50. Strings and Text Processing
  51. 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 = "Hello, C#"; s H e l l o , C # 51
  52. 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 52
  53. 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 = "Hello!"; int len = s.Length; // len = 6 char ch = s[1]; // ch = e index = 0 1 2 3 4 5 s[index] = H e l l o ! 53
  54. 54. Strings – Examplestatic void Main(){ string s = "Stand up, stand up, Balkan Superman."; Console.WriteLine("s = "{0}"", s); Console.WriteLine("s.Length = {0}", s.Length); for (int i = 0; i < s.Length; i++) { Console.WriteLine("s[{0}] = {1}", i, s[i]); }} 54
  55. 55. Declaring Strings There are two ways of declaring string variables:  Using the C# keyword string  Using the .NETs fully qualified class name System.String string str1; System.String str2; String str3;  The above three declarations are equivalent 55
  56. 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 56
  57. 57. Creating Strings (2) Not initialized variables has value of null string s; // s is equal to null Assigning a string literal string s = "I am a string literal!"; Assigning from another string variable string s2 = s; Assigning from the result of string operation string s = 42.ToString(); 57
  58. 58. Reading and Printing Strings Reading strings from the console  Use the method Console.ReadLine() string s = Console.ReadLine(); Printing strings to the console  Use the methods Write() and WriteLine() Console.Write("Please enter your name: "); string name = Console.ReadLine(); Console.Write("Hello, {0}! ", name); Console.WriteLine("Welcome to our party!"); 58
  59. 59. Comparing Strings A number of ways exist to compare two strings:  Dictionary-based string comparison  Case-insensitive int result = string.Compare(str1, str2, true); // result == 0 if str1 equals str2 // result < 0 if str1 if before str2 // result > 0 if str1 if after str2  Case-sensitive string.Compare(str1, str2, false); 59
  60. 60. Comparing Strings – Example Finding the first string in a lexicographical order from a given list of strings: string[] towns = {"Sofia", "Varna", "Plovdiv", "Pleven", "Bourgas", "Rousse", "Yambol"}; string firstTown = towns[0]; for (int i=1; i<towns.Length; i++) { string currentTown = towns[i]; if (String.Compare(currentTown, firstTown) < 0) { firstTown = currentTown; } } Console.WriteLine("First town: {0}", firstTown); 60
  61. 61. Concatenating Strings There are two ways to combine strings:  Using the Concat() method string str = String.Concat(str1, str2);  Using the + or the += operators string str = str1 + str2 + str3; string str += str1; Any object can be appended to string string name = "Peter"; int age = 22; string s = name + " " + age; //  "Peter 22" 61
  62. 62. Searching in Strings Finding a character or substring within given string  First occurrence IndexOf(string str)  First occurrence starting at given position IndexOf(string str, int startIndex)  Last occurrence LastIndexOf(string) 62
  63. 63. Searching in Strings – Example string str = "C# Programming Course"; int index = str.IndexOf("C#"); // index = 0 index = str.IndexOf("Course"); // index = 15 index = str.IndexOf("COURSE"); // index = -1 // IndexOf is case-sensetive. -1 means not found index = str.IndexOf("ram"); // index = 7 index = str.IndexOf("r"); // index = 4 index = str.IndexOf("r", 5); // index = 7 index = str.IndexOf("r", 8); // index = 18 index = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 …s[index] = C # P r o g r a m m i n g … 63
  64. 64. Extracting Substrings Extracting substrings  str.Substring(int startIndex, int length) string filename = @"C:PicsRila2009.jpg"; string name = filename.Substring(8, 8); // name is Rila2009  str.Substring(int startIndex) string filename = @"C:PicsSummer2009.jpg"; string nameAndExtension = filename.Substring(8); // nameAndExtension is Summer2009.jpg 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19C : P i c s R i l a 2 0 0 5 . j p g 64
  65. 65. Splitting Strings To split a string by given separator(s) use the following method: string[] Split(params char[]) Example: string listOfBeers = "Amstel, Zagorka, Tuborg, Becks."; string[] beers = listOfBeers.Split( , ,, .); Console.WriteLine("Available beers are:"); foreach (string beer in beers) { Console.WriteLine(beer); } 65
  66. 66. Replacing and Deleting Substrings Replace(string, string) – replaces all occurrences of given string with another  The result is new string (strings are immutable) string cocktail = "Vodka + Martini + Cherry"; string replaced = cocktail.Replace("+", "and"); // Vodka and Martini and Cherry Remove(index, length) – deletes part of a string and produces new string as result string price = "$ 1234567"; string lowPrice = price.Remove(2, 3); // $ 4567 66
  67. 67. Changing Character Casing Using method ToLower() string alpha = "aBcDeFg"; string lowerAlpha = alpha.ToLower(); // abcdefg Console.WriteLine(lowerAlpha); Using method ToUpper() string alpha = "aBcDeFg"; string upperAlpha = alpha.ToUpper(); // ABCDEFG Console.WriteLine(upperAlpha); 67
  68. 68. Trimming White Space Using method Trim() string s = " example of white space "; string clean = s.Trim(); Console.WriteLine(clean); Using method Trim(chars) string s = " tnHello!!! n"; string clean = s.Trim( , , ,!, n,t); Console.WriteLine(clean); // Hello Using TrimStart() and TrimEnd() string s = " C# "; string clean = s.TrimStart(); // clean = "C# " 68
  69. 69. Constructing Strings Strings are immutable  Concat(), Replace(), Trim(), ... return new string, do not modify the old one Do not use "+" for strings in a loop!  It runs very, very inefficiently! public static string DupChar(char ch, int count) { string result = ""; for (int i=0; i<count; i++) result += ch; return result; Very bad practice. } Avoid this! 69
  70. 70. Changing the Contents of a String – StringBuilder Use the System.Text.StringBuilder class for modifiable strings of characters: 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(); } Use StringBuilder if you need to keep adding characters to a string 70
  71. 71. The StringBuilder Class CapacityStringBuilder: H e l l o , C # ! Length=9 Capacity=15 used buffer unused (Length) buffer StringBuilder keeps a buffer memory, allocated in advance  Most operations use the buffer memory and do not allocate new objects 71
  72. 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(); } 72
  73. 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 = "The number is " + number.ToString(); Console.WriteLine(s); // The number is 5 73
  74. 74. Method ToString(format) We can applyspecific formatting when converting objects to string  ToString(formatString) method int number = 42; string s = number.ToString("D5"); // 00042 s = number.ToString("X"); // 2A // Consider the default culture is Bulgarian s = number.ToString("C"); // 42,00 лв double d = 0.375; s = d.ToString("P2"); // 37,50 % 74
  75. 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) 75
  76. 76. Method String.Format() Applies templates for formatting strings  Placeholders are used for dynamic text  Like Console.WriteLine(…) string template = "If I were {0}, I would {1}."; string sentence1 = String.Format( template, "developer", "know C#"); Console.WriteLine(sentence1); // If I were developer, I would know C#. string sentence2 = String.Format( template, "elephant", "weigh 4500 kg"); Console.WriteLine(sentence2); // If I were elephant, I would weigh 4500 kg. 76
  77. 77. Composite Formatting The placeholders in the composite formatting strings are specified as follows: {index[,alignment][:formatString]} Examples: double d = 0.375; s = String.Format("{0,10:F5}", d); // s = " 0,37500" int number = 42; Console.WriteLine("Dec {0:D} = Hex {1:X}", number, number); // Dec 42 = Hex 2A 77
  78. 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( "Now is {0:d.MM.yyyy HH:mm:ss}", now); // Now is 31.11.2009 11:30:32 78
  79. 79. Collection Classes Lists, Trees, Dictionaries
  80. 80. What are Generics? Generics allowdefining parameterized classes that process data of unknown (generic) type  The class can be instantiated with several different particular types  Example: List<T>  List<int> / List<string> / List<Student> Generics are also known as "parameterized types" or "template types"  Similar to the templates in C++  Similar to the generics in Java 80
  81. 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 81
  82. 82. List<T> – Simple Examplestatic void Main(){ List<string> list = new List<string>(); list.Add("C#"); list.Add("Java"); list.Add("PHP"); foreach (string item in list) { Console.WriteLine(item); } // Result: // C# // Java // PHP} 82
  83. 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 83
  84. 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 84
  85. 85. Primes in an Interval – Examplestatic 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;} 85
  86. 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 86
  87. 87. Stack<T> – Example Using Push(), Pop() and Peek() methods static void Main() { Stack<string> stack = new Stack<string>(); stack.Push("1. Ivan"); stack.Push("2. Nikolay"); stack.Push("3. Maria"); stack.Push("4. George"); Console.WriteLine("Top = {0}", stack.Peek()); while (stack.Count > 0) { string personName = stack.Pop(); Console.WriteLine(personName); } } 87
  88. 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 88
  89. 89. Queue<T> – Example Using Enqueue() and Dequeue() methods static void Main() { Queue<string> queue = new Queue<string>(); queue.Enqueue("Message One"); queue.Enqueue("Message Two"); queue.Enqueue("Message Three"); queue.Enqueue("Message Four"); while (queue.Count > 0) { string message = queue.Dequeue(); Console.WriteLine(message); } } 89
  90. 90. Dictionary<TKey,TValue> Class Implements the abstract data type "Dictionary" 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 90
  91. 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 91
  92. 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 92
  93. 93. Dictionary<TKey,Tvalue> – ExampleDictionary<string, int> studentsMarks = new Dictionary<string, int>();studentsMarks.Add("Ivan", 4);studentsMarks.Add("Peter", 6);studentsMarks.Add("Maria", 6);studentsMarks.Add("George", 5);int peterMark = studentsMarks["Peter"];Console.WriteLine("Peters mark: {0}", peterMark);Console.WriteLine("Is Peter in the hash table: {0}", studentsMarks.ContainsKey("Peter"));Console.WriteLine("Students and grades:");foreach (var pair in studentsMarks){ Console.WriteLine("{0} --> {1} ", pair.Key,pair.Value);} 93
  94. 94. Counting Words in Given Textstring text = "Welcome to our C# course. In this " + "course you will learn how to write simple " + "programs in C# and Microsoft .NET";string[] words = text.Split(new char[] { , ,, .}, StringSplitOptions.RemoveEmptyEntries);var wordsCount = new Dictionary<string, int>();foreach (string word in words){ if (wordsCount.ContainsKey(word)) wordsCount[word]++; else wordsCount.Add(word, 1);}foreach (var pair in wordsCount){ Console.WriteLine("{0} --> {1}", pair.Key, pair.Value);} 94
  95. 95. Balanced Trees in .NET Balanced Binary Search Trees  Ordered binary search trees that have height of log2(n) where n is the number of their nodes  Searching costs about log2(n) comparisons .NET Framework has built-in implementations of balanced search trees, e.g.:  SortedDictionary<K,V>  Red-black tree based map of key-value pairs External libraries like "Wintellect Power Collections for .NET" are more flexible 95
  96. 96. Sorted Dictionary – Examplestring text = "Welcome to our C# course. In this " + "course you will learn how to write simple " + "programs in C# and Microsoft .NET";string[] words = text.Split(new char[] { , ,, .}, StringSplitOptions.RemoveEmptyEntries);var wordsCount = new SortedDictionary<string, int>();foreach (string word in words){ if (wordsCount.ContainsKey(word)) wordsCount[word]++; else wordsCount.Add(word, 1);}foreach (var pair in wordsCount){ Console.WriteLine("{0} --> {1}", pair.Key, pair.Value);} 96
  97. 97. AttributesWhat They Are? How and When to Use Them?
  98. 98. What Are Attributes? Special declarativetags for attaching descriptive information (annotations) to the declarations in the code At compile time attributes are saved in the assemblys metadata Can be extracted from the metadata and can be manipulated by different tools Instances of classes derived from System.Attribute 98
  99. 99. Attributes Applying – Example Attributes name is surrounded by square brackets and is placed before the declaration which it refers to: [Flags] // System.FlagsAttribute public enum FileAccess { Read = 1, Write = 2, ReadWrite = Read | Write } [Flags] attribute indicates that the enum type can be treated like a set of bit flags 99
  100. 100. Attributes With Parameters Attributes use parameters for initialization: [DllImport("user32.dll", EntryPoint="MessageBox")] public static extern int ShowMessageBox(int hWnd, string text, string caption, int type); ... ShowMessageBox(0, "Some text", "Some caption", 0); 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 100
  101. 101. CSharp Language Overview курсове и уроци по програмиране, уеб дизайн – безплатно BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране – Телерик академия форум програмиране, форум уеб дизайн уроци по програмиране и уеб дизайн за ученици ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NET http://academy.telerik.com програмиране за деца – безплатни курсове и уроци ASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC безплатен SEO курс - оптимизация за търсачки алго академия – състезателно програмиране, състезаниякурсове и уроци по програмиране, книги – безплатно от Наков курс мобилни приложения с iPhone, Android, WP7, PhoneGap уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop Дончо Минков - сайт за програмиране free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране безплатен курс "Качествен програмен код" безплатен курс "Разработка на софтуер в cloud среда" C# курс, програмиране, безплатно
  102. 102. Free Trainings @ Telerik Academy "C# and Databases " course @ Telerik Academy  academy.telerik.com/…csharp-databases Telerik Software Academy  academy.telerik.com Telerik Academy @ Facebook  facebook.com/TelerikAcademy Telerik Software Academy Forums  forums.academy.telerik.com 102
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×