C language overview part ii l.jpg
This presentation is the property of its rightful owner.
Sponsored Links
1 / 102

C# Language Overview (Part II) PowerPoint PPT Presentation

  • Uploaded on
  • Presentation posted in: General

C# Language Overview (Part II). Creating and Using Objects, Exceptions, Strings, Generics, Collections, Attributes. http://schoolacademy.telerik.com . Svetlin Nakov. Telerik Corporation. www.telerik.com. Table of Contents. Creating and Using Objects Namespaces Exceptions Handling

Download Presentation

C# Language Overview (Part II)

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript

C language overview part ii l.jpg

C# Language Overview(Part II)

Creating and Using Objects, Exceptions, Strings, Generics, Collections, Attributes


Svetlin Nakov

Telerik Corporation


Table of contents l.jpg

Table of Contents

  • Creating and Using Objects

  • Namespaces

  • Exceptions Handling

  • Strings and Text Processing

  • Generics

  • Collection Classes

  • Attributes

Using classes and objects l.jpg

Using Classes and Objects

Using the Built-In .NET Framework Classes

What is class l.jpg

What is Class?

  • The formal definition of class:

    Definition by Google

Classes act as templates from which an instance of an object is created at run time. Classes define the properties of the object and the methods used to control the object's behavior.

Classes l.jpg


  • Classes provide the structure for objects

    • Define their prototype, act as template

  • Classes define:

    • Set of attributes

      • Represented by fields and properties

      • Hold their state

    • Set of actions (behavior)

      • Represented by methods

  • A class defines the methods and types of data associated with an object

Classes example l.jpg

Classes – Example

Class Name


(Properties and Fields)


+Owner: Person

+Ammount: double






Objects l.jpg


  • An object is a concrete instance of a particular class

  • Creating an object from a class is called instantiation

  • Objects have state

    • Set of values associated to their attributes

  • Example:

    • Class: Account

    • Objects: Ivan's account, Peter's account

Objects example l.jpg

Objects – Example




+Owner="Ivan Kolev"



+Owner: Person

+Ammount: double



+Owner="Peter Kirov"







+Owner="Kiril Kirov"


Classes in c l.jpg

Classes in C#

  • Basic units that compose programs

  • Implementation is encapsulated (hidden)

  • Classes in C# can contain:

    • Fields (member variables)

    • Properties

    • Methods

    • Constructors

    • Inner types

    • Etc. (events, indexers, operators, …)

Classes in c examples l.jpg

Classes in C# – Examples

  • Example of classes:

    • System.Console

    • System.String (string in C#)

    • System.Int32 (int in C#)

    • System.Array

    • System.Math

    • System.Random

Declaring objects l.jpg

Declaring Objects

  • An instance of a class or structure can be defined like any other variable:

  • Instances cannot be used if they are not initialized

using System;


// Define two variables of type DateTime

DateTime today;

DateTime halloween;

// Declare and initialize a structure instance

DateTime today = DateTime.Now;

Fields l.jpg


  • Fields are data members of a class

  • Can be variables and constants

  • Accessing a field doesn’t invoke any actions of the object

  • Example:

    • String.Empty (the "" string)

Accessing fields l.jpg

Accessing Fields

  • Constant fields can be only read

  • Variable fields can be read and modified

  • Usually properties are used instead of directly accessing variable fields

  • Examples:

// Accessing read-only field

String empty = String.Empty;

// Accessing constant field

int maxInt = Int32.MaxValue;

Properties l.jpg


  • Properties look like fields (have name and type), but they can contain code, executed when they are accessed

  • Usually used to control access to data fields (wrappers), but can contain more complex logic

  • Can have two components (and at least one of them) called accessors

    • get for reading their value

    • set for changing their value

Properties 2 l.jpg

Properties (2)

  • According to the implemented accessors properties can be:

    • Read-only (get accessor only)

    • Read and write (both get and setaccessors)

    • Write-only (set accessor only)

  • Example of read-only property:

    • String.Length

Accessing properties and fields example l.jpg

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;


"Christmas day: {0}, month: {1}, year: {2}",

day, month, year);


"Day of year: {0}", christmas.DayOfYear);

Console.WriteLine("Is {0} leap year: {1}",

year, DateTime.IsLeapYear(year));

Instance and static members l.jpg

Instance and Static Members

  • Fields, properties and methods can be:

    • Instance (or object members)

    • Static (or class members)

  • Instancemembers are specific for each object

    • Example: different dogs have different name

  • Staticmembers are common for all instances of a class

    • Example: DateTime.MinValue is shared between all instances of DateTime

Instance and static members examples l.jpg

Instance and Static Members – Examples

  • Example of instance member

    • String.Length

      • Each string object has different length

  • Example of static member

    • Console.ReadLine()

      • The console is only one (global for the program)

      • Reading from the console does not require to create an instance of it

Methods l.jpg


  • Methods manipulate the data of the object to which they belong or perform other tasks

  • Examples:

    • Console.WriteLine(…)

    • Console.ReadLine()

    • String.Substring(index, length)

    • Array.GetLength(index)

Instance methods l.jpg

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


Calling instance methods examples l.jpg

Calling Instance Methods – Examples

  • Calling instance methods of String:

  • Calling instance methods of DateTime:

String sampleLower = new String('a', 5);

String sampleUpper = sampleLower.ToUpper();

Console.WriteLine(sampleLower); // aaaaa

Console.WriteLine(sampleUpper); // AAAAA

DateTime now = DateTime.Now;

DateTime later = now.AddHours(8);

Console.WriteLine("Now: {0}", now);

Console.WriteLine("8 hours later: {0}", later);

Static methods l.jpg

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


Calling static methods examples l.jpg

Calling Static Methods – Examples

Constant field

Static method

using System;

double radius = 2.9;

double area = Math.PI * Math.Pow(radius, 2);

Console.WriteLine("Area: {0}", area);

// Area: 26,4207942166902

double precise = 8.7654321;

double round3 = Math.Round(precise, 3);

double round1 = Math.Round(precise, 1);


"{0}; {1}; {2}", precise, round3, round1);

// 8,7654321; 8,765; 8,8

Static method

Static method

Constructors l.jpg


  • Constructors are special methods used to assign initial values of the fields in an object

    • Executed when an object of a given type is being created

    • Have the same name as the class that holds them

    • Do not return a value

  • A class may have several constructors with different set of parameters

Constructors 2 l.jpg

Constructors (2)

  • Constructor is invoked by the new operator

  • Examples:

<instance_name> = new <class_name>(<parameters>)

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);

Structures l.jpg


  • Structures are similar to classes

  • Structures are usually used for storing data structures, without any other functionality

  • Structures can have fields, properties, etc.

    • Using methods is not recommended

  • Structures are value types, and classes are reference types (this will be discussed later)

  • Example of structure

    • System.DateTime– represents a date and time

Enumerations l.jpg


  • Enumerations in C# are types whose values are limited to a predefined set of values

    • E.g. the days of week

    • Declared by the keyword enum in C#

    • Hold values from a predefined set

public enum Color { Red, Green, Blue, Black }

Color color = Color.Red;

Console.WriteLine(color); // Red

color = 5; // Compilation error!

What is a namespace l.jpg

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, e.g.

    • Systemnamespace contains Data namespace

    • The name of the nested namespace is System.Data

Full class names l.jpg

Full Class Names

  • A full name of a class is the name of the class preceded by the name of its namespace

  • Example:

    • Array class, defined in the System namespace

    • The full name of the class is System.Array


Including namespaces l.jpg

Including Namespaces

  • The usingdirective in C#:

  • Allows using types in a namespace, without specifying their full name

  • Example:

    instead of

using <namespace_name>

using System;

DateTime date;

System.DateTime date;

Common type system cts l.jpg

Common Type System (CTS)

  • CTS defines all data types supported in .NET Framework

    • Primitive types (e.g. int, float, object)

    • Classes (e.g. String, Console, Array)

    • Structures (e.g. DateTime)

    • Arrays (e.g. int[], string[,])

    • Etc.

  • Object-oriented by design

Cts and different languages l.jpg

CTS and Different Languages

  • CTS is common for all .NET languages

    • C#, VB.NET, J#, JScript.NET, ...

  • CTS type mappings:

Value and reference types l.jpg

Value and Reference Types

  • In CTS there are two categories of types

    • Valuetypes

    • Reference types

  • Placed in different areas of memory

    • Value types live in the execution stack

      • Freed when become out of scope

    • Reference types live in the managed heap (dynamic memory)

      • Freed by the garbage collector

Value and reference types examples l.jpg

Value and Reference Types – Examples

  • Value types

    • Most of the primitive types

    • Structures

    • Examples: int, float, bool, DateTime

  • Reference types

    • Classes and interfaces

    • Strings

    • Arrays

    • Examples: string, Random, object, int[]

Exceptions handling l.jpg

The Paradigm of Exceptions in OOP

Exceptions Handling

What are exceptions l.jpg

What are Exceptions?

  • The exceptions in .NET Framework are classic implementation of the OOP exception model

  • Deliver powerful mechanism for centralized handling of errors and unusual events

  • Substitute procedure-oriented approach, in which each function returns error code

  • Simplify code construction and maintenance

  • Allow the problematic situations to be processed at multiple levels

Handling exceptions l.jpg

Handling Exceptions

  • In C# the exceptions can be handled by thetry-catch-finallyconstruction

  • catchblocks can be used multiple times to process different exception types



// Do some work that can raise an exception


catch (SomeException)


// Handle the caught exception


Handling exceptions example l.jpg

Handling Exceptions – Example

static void Main()


string s = Console.ReadLine();





"You entered valid Int32 number {0}.", s);


catch (FormatException)


Console.WriteLine("Invalid integer number!");


catch (OverflowException)



"The number is too big to fit in Int32!");



The system exception class l.jpg

TheSystem.Exception Class

  • Exceptions in .NET are objects

  • TheSystem.Exceptionclass is base for all exceptions in CLR

    • Holds 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 currentexception (if any)

Exception properties example l.jpg

Exception Properties – Example

class ExceptionsTest


public static void CauseFormatException()


string s = "an invalid number";



static void Main()






catch (FormatException fe)


Console.Error.WriteLine("Exception caught:{0}\n{1}",fe.Message, fe.StackTrace);




Exception properties l.jpg

Exception Properties

  • TheMessage property gives brief description of the problem

  • TheStackTrace property is extremely useful when identifying the reason caused the exception

Exception caught: Input string was not in a correct format.

at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)

at System.Int32.Parse(String s)

at ExceptionsTest.CauseFormatException() in c:\consoleapplication1\exceptionstest.cs:line 8

at ExceptionsTest.Main(String[] args) in c:\consoleapplication1\exceptionstest.cs:line 15

Exception properties 2 l.jpg

Exception Properties (2)

  • File names and line numbers are accessible only if the compilation was in Debugmode

  • When compiled in Release mode, the information in the property StackTraceis quite different:

Exception caught: Input string was not in a correct format.

at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)

at ExceptionsTest.Main(String[] args)

Exception hierarchy l.jpg

Exception Hierarchy

  • Exceptions in .NET Framework are organized in a hierarchy

Types of exceptions l.jpg

Types of Exceptions

  • All .NET exceptions inherit from System.Exception

  • The system exceptions inherit from System.SystemException, e.g.

    • System.ArgumentException

    • System.NullReferenceException

    • System.OutOfMemoryException

    • System.StackOverflowException

  • User-defined exceptions should inherit from System.ApplicationException

Handling exceptions45 l.jpg

Handling Exceptions

  • When catching an exception of a particular class, all its inheritors (child exceptions) are caught too

  • Example:

  • HandlesArithmeticExceptionandits successorsDivideByZeroExceptionandOverflowException



// Do some works that can raise an exception


catch (System.ArithmeticException)


// Handle the caught arithmetic exception


Handling all exceptions l.jpg

Handling All Exceptions

  • All exceptions thrown by .NET managed code inherit the System.Exceptionexception

  • Unmanaged code can throw other exceptions

  • For handling all exceptions (even unmanaged) use the construction:



// Do some works that can raise any exception




// Handle the caught exception


Throwing exceptions l.jpg

Throwing Exceptions

  • Exceptions are thrown (raised) by throw keyword in C#

    • Used to notify the calling code in case of error or unusual situation

  • When an exception is thrown:

    • The program execution stops

    • The exception travels over the stack until a suitable catch block is reached to handle it

  • Unhandled exceptions display error message

How exceptions work l.jpg

How Exceptions Work?

5. Throw an exception

Method N

Method N

6. Find handler

4. Method call

Method 2

Method 2

3. Method call

7. Find handler

Method 1

Method 1

2. Method call

8. Find handler




9. Find handler

1. Execute the


10. Display error message

Using throw keyword l.jpg

Using throw Keyword

  • Throwing an exception with error message:

  • Exceptions can take message and cause:

  • Note:if the original exception is not passed the initial cause of the exception is lost

throw new ArgumentException("Invalid amount!");





catch (FormatException fe)


throw new ArgumentException("Invalid number", fe);


Throwing exceptions example l.jpg

Throwing Exceptions – Example

public 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()






catch (ArgumentOutOfRangeException ex)


Console.Error.WriteLine("Error: " + ex.Message);




Strings and text processing l.jpg

Strings and Text Processing

What is string l.jpg

What Is String?

  • Strings are sequences of characters

  • Each character is a Unicode symbol

  • Represented by the stringdata type in C# (System.String)

  • Example:

string s = "Hello, C#";


The system string class l.jpg

The System.String Class

  • Strings are represented by System.String objects in .NET Framework

    • String objects contain an immutable (read-only) sequence of characters

    • Strings use Unicode in to support multiple languages and alphabets

  • Strings are stored in the dynamic memory (managed heap)

  • System.String is reference type

The system string class 2 l.jpg

The System.StringClass (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 = 6char ch = s[1]; // ch = 'e'

index =

s[index] =

Strings example l.jpg

Strings – Example

static void Main()


string s =

"Stand up, stand up, Balkan Superman.";

Console.WriteLine("s = \"{0}\"", s);

Console.WriteLine("s.Length = {0}", s.Length);

for (int i = 0; i < s.Length; i++)


Console.WriteLine("s[{0}] = {1}", i, s[i]);



Declaring strings l.jpg

Declaring Strings

  • There are two ways of declaring string variables:

    • Usingthe C# keywordstring

    • Using the .NET's fully qualified class name System.String

    • The above three declarations are equivalent

string str1;

System.String str2;

String str3;

Creating strings l.jpg

Creating Strings

  • Before initializing a string variable has nullvalue

  • Strings can be initialized by:

    • Assigning a string literal to the string variable

    • Assigning the value of another string variable

    • Assigning the result of operation of type string

Creating strings 2 l.jpg

Creating Strings (2)

  • Not initialized variables has value of null

  • Assigning a string literal

  • Assigning from another string variable

  • Assigning from the result of string operation

string s; // s is equal to null

string s = "I am a string literal!";

string s2 = s;

string s = 42.ToString();

Reading and printing strings l.jpg

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!");

Comparing strings l.jpg

Comparing Strings

  • A number of ways exist to compare two strings:

    • Dictionary-based string comparison

      • Case-insensitive

      • Case-sensitive

int result = string.Compare(str1, str2, true);

// result == 0 if str1 equals str2

// result < 0 if str1 if before str2

// result > 0 if str1 if after str2

string.Compare(str1, str2, false);

Comparing strings example l.jpg

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);

Concatenating strings l.jpg

Concatenating Strings

  • There are two ways to combine strings:

    • Using the Concat() method

    • Using the + or the += operators

  • Any object can be appended to a string

string str = String.Concat(str1, str2);

string str = str1 + str2 + str3;

string str += str1;

string name = "Peter";

int age = 22;

string s = name + " " + age; //  "Peter 22"

Searching in strings l.jpg

Searching in Strings

  • Finding a character or substring within given string

    • First occurrence

    • First occurrence starting at given position

    • Last occurrence

IndexOf(string str)

IndexOf(string str, int startIndex)


Searching in strings example l.jpg

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 =

s[index] =

Extracting substrings l.jpg

Extracting Substrings

  • Extracting substrings

    • str.Substring(int startIndex, int length)

    • str.Substring(int startIndex)

string filename = @"C:\Pics\Rila2009.jpg";

string name = filename.Substring(8, 8);

// name is Rila2009

string filename = @"C:\Pics\Summer2009.jpg";

string nameAndExtension = filename.Substring(8);

// nameAndExtension is Summer2009.jpg

Splitting strings l.jpg

Splitting Strings

  • To split a string by given separator(s) use the following method:

  • Example:

string[] Split(params char[])

string listOfBeers =

"Amstel, Zagorka, Tuborg, Becks.";

string[] beers =

listOfBeers.Split(' ', ',', '.');

Console.WriteLine("Available beers are:");

foreach (string beer in beers)




Replacing and deleting substrings l.jpg

Replacing and Deleting Substrings

  • Replace(string,string) – replaces all occurrences of given string with another

    • The result is new string (strings are immutable)

  • Remove(index,length) – deletes part of a string and produces a new string as result

string cocktail = "Vodka + Martini + Cherry";

string replaced = cocktail.Replace("+", "and");

// Vodka and Martini and Cherry

string price = "$ 1234567";

string lowPrice = price.Remove(2, 3);

// $ 4567

Changing character casing l.jpg

Changing Character Casing

  • Using method ToLower()

  • Using method ToUpper()

string alpha = "aBcDeFg";

string lowerAlpha = alpha.ToLower(); // abcdefg


string alpha = "aBcDeFg";

string upperAlpha = alpha.ToUpper(); // ABCDEFG


Trimming white space l.jpg

Trimming White Space

  • Using method Trim()

  • Using method Trim(chars)

  • Using TrimStart() and TrimEnd()

string s = " example of white space ";

string clean = s.Trim();


string s = " \t\nHello!!! \n";

string clean = s.Trim(' ', ',' ,'!', '\n','\t');

Console.WriteLine(clean); // Hello

string s = " C# ";

string clean = s.TrimStart(); // clean = "C# "

Constructing strings l.jpg

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 (slowly)!

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!

Changing the contents of a string stringbuilder l.jpg

Changing the Contents of a String – StringBuilder

  • Use the System.Text.StringBuilder class for modifiable strings of characters:

  • Use StringBuilder if you need to keep adding characters to a string

public static string ReverseString(string s)


StringBuilder sb = new StringBuilder();

for (int i = s.Length-1; i >= 0; i--)


return sb.ToString();


The stringbuilde r class l.jpg

The StringBuilder Class

  • StringBuilder keeps a buffer memory, allocated in advance

    • Most operations use the buffer memory and do not allocate new objects


  • StringBuilder:

    • Length=9

    • Capacity=15

unused buffer

used buffer


Stringbuilder example l.jpg

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]))





return result.ToString();


Method tostring l.jpg

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

Method tostring format l.jpg

Method ToString(format)

  • We can apply specific 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 %

Formatting strings l.jpg

Formatting Strings

  • The formatting strings are different for the different types

  • Some formatting strings for numbers:

    • D – number (for integer types)

    • C – currency (according to current culture)

    • E – number in exponential notation

    • P – percentage

    • X – hexadecimal number

    • F – fixed point (for real numbers)

Method string format l.jpg

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#");


// If I were developer, I would know C#.

string sentence2 = String.Format(

template, "elephant", "weigh 4500 kg");


// If I were elephant, I would weigh 4500 kg.

Composite formatting l.jpg

Composite Formatting

  • The placeholders in the composite formatting strings are specified as follows:

  • Examples:


double d = 0.375;

s = String.Format("{0,10:F5}", d);

// s = " 0,37500"

int number = 42;


"Dec {0:D} = Hex {1:X}", number, number);

// Dec 42 = Hex 2A

Formatting dates l.jpg

Formatting Dates

  • Dates use 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;


"Now is {0:d.MM.yyyy hh:mm:ss}", now);

// Now is 31.11.200911:30:32

Collection classes l.jpg

Collection Classes

Lists, Trees, Dictionaries

What are generics l.jpg

What are Generics?

  • Generics allow defining parameterized classes that process data of unknown (generic) type

    • The class can be instantiated with several different particular types

    • Example: List<T> List<int> / List<string> / List<Student>

  • Generics are also known as "parameterizedtypes" or "template types"

    • Similar to the templates in C++

    • Similar to the generics in Java

The list t class l.jpg

The List<T> Class

  • Implements the abstract data structure list using an auto-extensible array

    • All elements are of the same type T

    • Tcan be any type, e.g. List<int>, List<string>, List<DateTime>

    • Size is dynamically increased as needed

  • Basic functionality:

    • Count – returns the number of elements

    • Add(T) – appends given element at the end

List t simple example l.jpg

List<T> – Simple Example

static void Main()


List<string> list = new List<string>();




foreach (string item in list)




// Result:

// C#

// Java

// PHP


List t functionality l.jpg

List<T> – Functionality

  • list[index] – access element by index

  • Insert(index,T) – inserts given element to the list at a specified position

  • Remove(T) – removes the first occurrence of given element

  • RemoveAt(index)– removes the element at the specified position

  • Clear() – removes all elements

  • Contains(T) – determines whether an element is part of the list

List t functionality 2 l.jpg

List<T> – Functionality (2)

  • IndexOf() – returns the index of the first occurrence of a valuein the list (zero-based)

  • Reverse() – reverses the order of the elements in the list or a portion of it

  • Sort() – sorts the elements in the list or a portion of it

  • ToArray() – converts the elements of the list to an array

  • TrimExcess() – sets the capacity to the actual number of elements

Primes in an interval example l.jpg

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;




if (prime)





return primesList;


The stack t class l.jpg

The Stack<T> Class

  • Implements the stack data structure using an array

    • Elements are of the same type T

    • Tcan be any type, e.g. Stack<int>

    • Size is dynamically increased as needed

  • Basic functionality:

    • Push(T)– inserts elements to the stack

    • Pop()– removes and returns the top element from the stack

Stack t example l.jpg

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();




The queue t class l.jpg

The Queue<T> Class

  • Implements the queue data structure using a circular resizable array

    • Elements are from the same type T

    • Tcan be any type, e.g. Stack<int>

    • Size is dynamically increased as needed

  • Basic functionality:

    • Enqueue(T)– adds an element to the end of the queue

    • Dequeue()– removes and returns the element at the beginning of the queue

Queue t example l.jpg


  • 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();




Dictionary tkey tvalue class l.jpg


  • Implements the abstract data type "Dictionary" as hash table

    • Size is dynamically increased as needed

    • Contains a collection of key-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 the elements

Dictionary tkey tvalue class 2 l.jpg

Dictionary<TKey,TValue>Class (2)

  • Object.GetHashCode() method for calculating the hash codes of the elements

  • Major operations:

    • Add(TKey,TValue)– adds an element with the specified key and value into the dictionary

    • Remove(TKey)– removes the element with the specified key

    • Clear()– removes all elements

    • this[] – returns element by key

  • Dictionary tkey tvalue class 3 l.jpg

    Dictionary<TKey,TValue>Class (3)

    • Count– returns the number of elements

    • ContainsKey(TKey)– determines whether the dictionary contains given key

    • ContainsValue(TValue) – determines whether the dictionary contains given value

    • Keys– returns a collection of the keys

    • Values – returns a collection of the values

    • TryGetValue(TKey,out TValue) – if the key is found, returns it in the TValue, otherwise returns the default value for the TValue type

    Dictionary tkey tvalue example l.jpg

    Dictionary<TKey,TValue> – Example

    Dictionary<string, int> studentsMarks = new Dictionary<string, int>();

    studentsMarks.Add("Ivan", 4);

    studentsMarks.Add("Peter", 6);

    studentsMarks.Add("Maria", 6);

    studentsMarks.Add("George", 5);

    int peterMark = studentsMarks["Peter"];

    Console.WriteLine("Peter's mark: {0}", peterMark);

    Console.WriteLine("Is Peter in the hash table: {0}",


    Console.WriteLine("Students and grades:");

    foreach (var pair in studentsMarks)


    Console.WriteLine("{0} --> {1} ", pair.Key, pair.Value);


    Counting words in given text l.jpg

    Counting Words in Given Text

    string 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[] {' ', ',', '.'},


    var wordsCount = new Dictionary<string, int>();

    foreach (string word in words)


    if (wordsCount.ContainsKey(word))



    wordsCount.Add(word, 1);


    foreach (var pair in wordsCount)


    Console.WriteLine("{0} --> {1}", pair.Key, pair.Value);


    Balanced trees in net l.jpg

    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

    Sorted dictionary example l.jpg

    Sorted Dictionary – Example

    string 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[] {' ', ',', '.'},


    var wordsCount = new SortedDictionary<string, int>();

    foreach (string word in words)


    if (wordsCount.ContainsKey(word))



    wordsCount.Add(word, 1);


    foreach (var pair in wordsCount)


    Console.WriteLine("{0} --> {1}", pair.Key, pair.Value);


    Attributes l.jpg


    What Attributes Are? How and When to Use Them?

    What are attributes l.jpg

    What Are Attributes?

    • Attributes are special declarative tags

      • Used for attaching descriptive information (annotations) to the declarations in the code

    • At compile time attributes are saved in the assembly's metadata

      • Can be extracted from the metadata at run-time and can be manipulated by different tools

    • Instances of classes derived from System.Attribute

    Attributes applying example l.jpg

    Attributes Applying – Example

    • Attribute's name is surrounded by square brackets and is placed before the declaration which it refers to:

    • [Flags] attribute indicates that the enumtype can be treatedlike a set of bit flags

    [Flags] // System.FlagsAttribute

    public enum FileAccess


    Read = 1,

    Write = 2,

    ReadWrite = Read | Write


    Attributes with parameters l.jpg

    Attributes With Parameters

    • Attributes use parameters for initialization:

    • In this example the [DllImport]attribute isinstantiated by the compiler

      • A System.Runtime.InteropServices. DllImportAttribute object is created, initialized and put into the assembly metadata

    [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);

    C language overview part ii102 l.jpg

    C# Language Overview(Part II)













  • Login