C# Advanced Topics Methods, Arrays, Lists, Dictionaries, Strings, Classes and Objects SoftUni Team Technical Trainers Software University

Slides:



Advertisements
Similar presentations
Software Quality Assurance QA Engineering, Testing, Bug Tracking, Test Automation Software University Technical Trainers SoftUni Team.
Advertisements

 Dimitar Ivanov Introduction to programming with microcontrollers.
C# Advanced Topics Methods, Classes and Objects SoftUni Team Technical Trainers Software University
Methods Writing and using methods, overloads, ref, out SoftUni Team Technical Trainers Software University
Software University Curriculum, Courses, Exams, Jobs SoftUni Team Technical Trainers Software University
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Loops, Methods, Classes Loops, Methods, Using API Classes, Exceptions SoftUni Team Technical Trainer Software University
Programming Basics Course Introduction SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
Teamwork and Personal Skills Course Introduction Software University SoftUni Team Technical Trainers.
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Course Program, Evaluation, Exams
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
Database APIs and Wrappers
Entity Framework Performance SoftUni Team Technical Trainers Software University
Methods, Arrays, Lists, Dictionaries, Strings, Classes and Objects
Svetlin Nakov Technical Trainer Software University
Build Processes and Continuous Integration Automating Build Processes Software University Technical Trainers SoftUni Team.
Processing Redis with.NET How to Operate with Redis Databases SoftUni Team Technical Trainers Software University
Multidimensional Arrays, Sets, Dictionaries Processing Matrices, Multidimensional Arrays, Dictionaries, Sets SoftUni Team Technical Trainers Software University.
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
Defining Classes Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University
Java Collections Basics Arrays, Lists, Strings, Sets, Maps Svetlin Nakov Technical Trainer Software University
Arrays, Lists, Stacks, Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
C# Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Defining Classes Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Technical Trainer Software University
Java Collections Arrays, Lists, Strings, Sets, Maps SoftUni Team Technical Trainers Software University
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
Exam Preparation Algorithms Course: Sample Exam SoftUni Team Technical Trainers Software University
Console Input / Output Reading and Writing to the Console SoftUni Team Technical Trainers Software University
Processing JSON in.NET JSON, JSON.NET LINQ-to-JSON and JSON to XML SoftUni Team Technical Trainers Software University
Associative Arrays and Objects Associative Arrays, Objects Svetlin Nakov Technical Trainer Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability Svetlin Nakov Technical Trainer Software University
High-Quality Code: Course Introduction Course Introduction SoftUni Team Technical Trainers Software University
Java Collections Basics Arrays, Lists, Strings, Sets, Maps Bogomil Dimitrov Technical Trainer Software University
Design Patterns: Structural Design Patterns General and reusable solutions to common problems in software design Software University
Advanced C# Course Introduction SoftUni Team Technical Trainers Software University
Object-Oriented Programming Course Introduction Svetlin Nakov Technical Trainer Software University
Reflection Programming under the hood SoftUni Team Technical Trainers Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Operators and Expressions
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
Programming for Beginners Course Introduction SoftUni Team Technical Trainers Software University
Processing Sequences of Elements
Strings, Dictionaries, Lambda and LINQ Text Processing, Dictionaries, Lambda Functions, LINQ SoftUni Team Technical Trainers Software University
Objects and Classes Using Objects and Classes Defining Simple Classes SoftUni Team Technical Trainers Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
Lists and Matrices Lists: Variable-Size Arrays Matrices: Arrays of Arrays (Tables) SoftUni Team Technical Trainers Software University
SoftUni Team Technical Trainers Software University Trees and Tree-Like Structures Trees, Tree-Like Structures, Binary Search Trees,
Advanced Tree Structures Binary Trees, AVL Tree, Red-Black Tree, B-Trees, Heaps SoftUni Team Technical Trainers Software University
Loops, Methods, Classes Using Loops, Defining and Using Methods, Using API Classes, Exceptions, Defining Classes Svetlin Nakov Technical Trainer
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Programming Fundamentals Course Introduction SoftUni Team Technical Trainers Software University
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Static Members Static Variables & Methods SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
C# Basic Syntax, Visual Studio, Console Input / Output
Repeating Code Multiple Times
Methods, Arrays, Lists, Dictionaries, Strings, Classes and Objects
Text Processing and Regex API
Multidimensional Arrays
Presentation transcript:

C# Advanced Topics Methods, Arrays, Lists, Dictionaries, Strings, Classes and Objects SoftUni Team Technical Trainers Software University

Table of Contents  A very brief introduction to:  Methods  Using Built-in.NET Classes  Arrays  Lists  Dictionaries  Strings  Defining Simple Classes 2

Methods Defining and Invoking Methods

4  Methods are named pieces of code  Defined in the class body  Can be invoked multiple times  Can take parameters  Can return a value Methods: Defining and Invoking static void PrintHyphens(int count) { Console.WriteLine( Console.WriteLine( new string('-', count)); new string('-', count));} static void Main() { for (int i = 1; i <= 10; i++) for (int i = 1; i <= 10; i++) { PrintHyphens(i); PrintHyphens(i); }}

5 Methods with Parameters and Return Value static double CalcTriangleArea(double width, double height) { return width * height / 2; return width * height / 2;} static void Main() { Console.Write("Enter triangle width: "); Console.Write("Enter triangle width: "); double width = double.Parse(Console.ReadLine()); double width = double.Parse(Console.ReadLine()); Console.Write("Enter triangle height: "); Console.Write("Enter triangle height: "); double height = double.Parse(Console.ReadLine()); double height = double.Parse(Console.ReadLine()); Console.WriteLine(CalcTriangleArea(width, height)); Console.WriteLine(CalcTriangleArea(width, height));}

Methods Live Demo

Using Built-in.NET Classes Math, Random, Console, etc.

8 .NET Framework provides thousands of ready-to-use classes  Packaged into namespaces like System, System.Net, System.Collections, System.Linq, etc.  Using static.NET classes:  Using non-static.NET classes Built-in Classes in.NET Framework DateTime today = DateTime.Now; double cosine = Math.Cos(Math.PI); Random rnd = new Random(); int randomNumber = rnd.Next(1, 99);

9 Built-in.NET Classes – Examples DateTime today = DateTime.Now; Console.WriteLine("Today is: " + today); DateTime tomorrow = today.AddDays(1); Console.WriteLine("Tomorrow is: " + tomorrow); double angleDegrees = 60; double angleRadians = angleDegrees * Math.PI / 180; Console.WriteLine(Math.Cos(angleRadians)); Random rnd = new Random(); Console.WriteLine(rnd.Next(1,100)); WebClient webClient = new WebClient(); webClient.DownloadFile(" "file.pdf"); webClient.DownloadFile(" … ", "file.pdf");Process.Start("file.pdf");

Using Built-in.NET Classes Live Demo

Arrays Working with Arrays of Elements

What are Arrays?  In programming array is a sequence of elements  All elements are of the same type  The order of the elements is fixed  Has fixed size ( Array.Length ) Array of 5 elements Element index Element of an array ……………

13  Allocating an array of 10 integers:  Assigning values to the array elements:  Accessing array elements by index: Working with Arrays int[] numbers = new int[10]; for (int i = 0; i < numbers.Length; i++) numbers[i] = i + 1; numbers[i] = i + 1; numbers[3] = 20; numbers[5] = numbers[2] + numbers[7];

14  Printing an array:  Finding sum, minimum, maximum, first, last element: Working with Arrays (2) for (int i = 0; i < numbers.Length; i++) Console.WriteLine("numbers[{0}] = {1}", i, numbers[i]); Console.WriteLine("numbers[{0}] = {1}", i, numbers[i]); Console.WriteLine("Sum = " + numbers.Sum()); Console.WriteLine("Min = " + numbers.Min()); Console.WriteLine("Max = " + numbers.Max()); Console.WriteLine("First = " + numbers.First()); Console.WriteLine("Last = " + numbers.Last()); Ensure you have using System.Linq; to use aggregate functions

15  You may define an array of any type, e.g. string : Arrays of Strings string[] names = { "Peter", "Maria", "Katya", "Todor" }; names.Reverse(); names[0] = names[0] + " (junior)"; foreach (var name in names) { Console.WriteLine(name); Console.WriteLine(name);} names[4] = "Nakov"; // This will cause an exception!

16  We want to build the matrix on the right Two-dimensional Arrays (Matrices) aaabacad babbbcbd cacbcccd dadbdcdd eaebeced fafbfcfd int width = 4, height = 6; string[,] matrix = new string[height, width]; new string[height, width]; for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) for (int col = 0; col < width; col++) { matrix[row, col] = "" + matrix[row, col] = "" + (char)('a' + row) + (char)('a' + row) + (char)('a' + col); (char)('a' + col); }}

Arrays and Matrices Live Demo

Lists of Elements Working with List

19  In C# arrays have fixed length  Cannot add / remove / insert elements  Lists are like resizable arrays  Allow add / remove / insert of elements  Lists in C# are defined through the List class  Where T is the type of the list, e.g. string or int Lists List numbers = new List (); numbers.Add(5); Console.WriteLine(numbers[0]); // 5

20 List – Example List names = new List () { "Peter", "Maria", "Katya", "Todor" }; new List () { "Peter", "Maria", "Katya", "Todor" }; names.Add("Nakov"); // Peter, Maria, Katya, Todor, Nakov names.RemoveAt(0); // Maria, Katya, Todor, Nakov names.Insert(3, "Sylvia"); // Maria, Katya, Todor, Sylvia, Nakov names[1] = "Michael"; // Maria, Michael, Todor, Sylvia, Nakov foreach (var name in names) { Console.WriteLine(name); Console.WriteLine(name);}

List Live Demo

Associative Arrays Dictionary

23  Associative arrays are arrays indexed by keys  Not by the numbers 0, 1, 2, …  Hold a set of pairs Associative Arrays (Maps, Dictionaries)  Traditional array  Associative array John Smith Lisa Smith Sam Doe key value key value

24 Phonebook – Example Dictionary phonebook = new Dictionary (); new Dictionary (); phonebook["John Smith"] = " "; phonebook["Lisa Smith"] = " "; phonebook["Sam Doe"] = " "; phonebook["Nakov"] = " "; phonebook["Nakov"] = " "; phonebook.Remove("John Smith"); foreach (var pair in phonebook) { Console.WriteLine("{0} --> {1}", entry.Key, entry.Value); Console.WriteLine("{0} --> {1}", entry.Key, entry.Value);}

25 Events – Example Dictionary events = new Dictionary (); new Dictionary (); events[new DateTime(1998, 9, 4)] = "Google's birth date"; events[new DateTime(2013, 11, 5)] = "SoftUni's birth date"; events[new DateTime(1975, 4, 4)] = "Microsoft's birth date"; events[new DateTime(2004, 2, 4)] = "Facebook's birth date"; events[new DateTime(2013, 11, 5)] = "Nakov left Telerik Academy to establish SoftUni"; "Nakov left Telerik Academy to establish SoftUni"; foreach (var entry in events) { Console.WriteLine("{0:dd-MMM-yyyy}: {1}", Console.WriteLine("{0:dd-MMM-yyyy}: {1}", entry.Key, entry.Value); entry.Key, entry.Value);}

Associative Arrays Live Demo

Strings Basic String Operations

What Is String?  Strings are indexed sequences of Unicode characters  Represented by the string data type in C#  Also known as System.String  Example: string s = "Hello, SoftUni!"; Hello, SoftUni!s

29  Strings in C#  Knows its number of characters – Length  Can be accessed by index ( 0 … Length-1 )  Strings are stored in the dynamic memory (managed heap)  Can have null value (missing value)  Strings cannot be modified (immutable)  Most string operations return a new string instance  StringBuilder class is used to build stings Working with Strings in C#

30 Strings – Examples string str = "SoftUni"; Console.WriteLine(str); for (int i = 0; i < str.Length; i++) { Console.WriteLine("str[{0}] = {1}", i, str[i]); Console.WriteLine("str[{0}] = {1}", i, str[i]);} Console.WriteLine(str.IndexOf("Uni")); // 4 Console.WriteLine(str.IndexOf("uni")); // -1 (not found) Console.WriteLine(str.Substring(4, 3)); // Uni Console.WriteLine(str.Replace("Soft", "Hard")); // HardUni Console.WriteLine(str.ToLower()); // softuni Console.WriteLine(str.ToUpper()); // SOFTUNI

31 Strings – Examples (2) string firstName = "Steve"; string lastName = "Jobs"; int age = 56; Console.WriteLine(firstName + " " + lastName + " (age: " + age + ")"); // Steve Jobs (age: 56) " (age: " + age + ")"); // Steve Jobs (age: 56) string allLangs = "C#, Java; HTML, CSS; PHP, SQL"; string[] langs = allLangs.Split(new char[] {',', ';', ' '}, StringSplitOptions.RemoveEmptyEntries); StringSplitOptions.RemoveEmptyEntries); foreach (var lang in langs) Console.WriteLine(lang); Console.WriteLine(lang); Console.WriteLine("Langs = " + string.Join(", ", langs)); Console.WriteLine(" \n\n Software University ".Trim());

Strings Live Demo

Defining Simple Classes Using Classes to Hold a Set of Fields

34  Classes in C# combine a set of named fields / properties  Defining a class Point holding X and Y coordinates:  Creating class instances (objects): Classes in C# class Point { public int X { get; set; } public int X { get; set; } public int Y { get; set; } public int Y { get; set; }} Point start = new Point() { X = 3, Y = 4 }; Point end = new Point() { X = -1, Y = 5 };

35  We can create arrays and lists of objects: Arrays of Objects Point[] line = new Point[] { new Point() { X = -2, Y = 1 }, new Point() { X = -2, Y = 1 }, new Point() { X = 1, Y = 3 }, new Point() { X = 1, Y = 3 }, new Point() { X = 4, Y = 2 }, new Point() { X = 4, Y = 2 }, new Point() { X = 3, Y = -2 }, new Point() { X = 3, Y = -2 },}; for (int i = 0; i < line.Length; i++) { Console.WriteLine("Point(" + line[i].X + ", " + line[i].Y + ")"); Console.WriteLine("Point(" + line[i].X + ", " + line[i].Y + ")");}

36 Defining and Using Classes – Example class Person { public string FirstName { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string LastName { get; set; } public int Age { get; set; } public int Age { get; set; }}… Person[] people = new Person[] { new Person() { FirstName = "Larry", LastName = "Page", Age = 40}, new Person() { FirstName = "Larry", LastName = "Page", Age = 40}, new Person() { FirstName = "Steve", LastName = "Jobs", Age = 56}, new Person() { FirstName = "Steve", LastName = "Jobs", Age = 56}, new Person() { FirstName = "Bill", LastName = "Gates", Age = 58}, new Person() { FirstName = "Bill", LastName = "Gates", Age = 58},};

37 Defining and Using Classes – Example (2) Console.WriteLine("Young people: "); foreach (var p in people) { if (p.Age < 50) if (p.Age < 50) { Console.WriteLine("{0} (age: {1})", p.LastName, p.Age); Console.WriteLine("{0} (age: {1})", p.LastName, p.Age); }} var youngPeople = people.Where(p => p.Age p.Age < 50); foreach (var p in youngPeople) { Console.WriteLine("{0} (age: {1})", p.LastName, p.Age); Console.WriteLine("{0} (age: {1})", p.LastName, p.Age);}

Defining and Using Simple Classes Live Demo

39  Methods are reusable named code blocks .NET Framework provides a rich class library  Arrays are indexed blocks of elements (fixed-length)  Lists are indexed sequences of elements (variable-length)  Dictionaries map keys to values and provide fast access by key  Strings are indexed sequences of characters  Classes combine a set of fields into a single structure  Objects are instances of classes Summary

? ? ? ? ? ? ? ? ? C# Advanced Topics

Homework Review Live Demo

License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 42  Attribution: this work may contain portions from  "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA licenseFundamentals of Computer Programming with C#CC-BY-SA  "C# Part I" course by Telerik Academy under CC-BY-NC-SA licenseC# Part ICC-BY-NC-SA

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg