11 using classes and objects

69
Using Classes and Using Classes and Objects Objects Using the Standard .NET Framework Using the Standard .NET Framework Classes Classes Svetlin Nakov Svetlin Nakov Telerik Telerik Corporation Corporation www.telerik. com

Upload: maznabili

Post on 26-Jun-2015

74 views

Category:

Technology


1 download

DESCRIPTION

Using classes and objects

TRANSCRIPT

Page 1: 11 Using classes and objects

Using Classes and Using Classes and ObjectsObjects

Using the Standard .NET Framework Using the Standard .NET Framework ClassesClasses

Svetlin NakovSvetlin NakovTelerik Telerik

CorporationCorporationwww.telerik.com

Page 2: 11 Using classes and objects

Table of ContentsTable of Contents

1.1. Classes and ObjectsClasses and Objects What are Objects? What are Objects? What are Classes? What are Classes?

2.2. Classes in C#Classes in C# Declaring ClassDeclaring Class Fields and Properties: Instance and Fields and Properties: Instance and

StaticStatic Instance and Static Methods Instance and Static Methods ConstructorsConstructors

3.3. StructuresStructures

Page 3: 11 Using classes and objects

Table of Contents (2)Table of Contents (2)

4.4. NamespacesNamespaces

5.5.RandomRandom classclass

6.6. Introduction to .NET Introduction to .NET Common Type SystemCommon Type System

Page 4: 11 Using classes and objects

Classes and Classes and ObjectsObjectsModeling Real-world Entities with Modeling Real-world Entities with

ObjectsObjects

Page 5: 11 Using classes and objects

What are Objects?What are Objects? Software objects model real-world Software objects model real-world

objects or abstract conceptsobjects or abstract concepts Examples: Examples:

bank, account, customer, dog, bicycle, bank, account, customer, dog, bicycle, queue queue

Real-world objects have Real-world objects have statesstates and and behaviorsbehaviors Account' states: Account' states:

holder, balance, typeholder, balance, type

Account' behaviors: Account' behaviors: withdraw, deposit, suspendwithdraw, deposit, suspend

Page 6: 11 Using classes and objects

What are Objects? (2)What are Objects? (2)

How do software objects How do software objects implement real-world objects?implement real-world objects? Use variables/data to implement Use variables/data to implement

statesstates Use methods/functions to Use methods/functions to

implement behaviorsimplement behaviors An object is a software bundle of An object is a software bundle of

variables and related methodsvariables and related methods

Page 7: 11 Using classes and objects

Objects RepresentObjects Represent

7

checkschecks

peoplepeople

shopping listshopping list

……

numbersnumbers

characterscharacters

queuesqueues

arraysarrays

Things Things from the from the real worldreal world

Things from Things from the the computer computer worldworld

Page 8: 11 Using classes and objects

What is Class?What is Class?

The formal definition of The formal definition of classclass::

Definition by GoogleDefinition by Google

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

Page 9: 11 Using classes and objects

ClassesClasses Classes provide the structure for objectsClasses provide the structure for objects

Define their prototype, act as templateDefine their prototype, act as template Classes define:Classes define:

Set of Set of attributesattributes Represented by variables and propertiesRepresented by variables and properties

Hold their Hold their statestate

Set of actions (Set of actions (behaviorbehavior)) Represented by methodsRepresented by methods

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

Page 10: 11 Using classes and objects

Classes – ExampleClasses – Example

AccountAccount

+Owner: Person+Owner: Person+Ammount: double+Ammount: double

+Suspend()+Suspend()+Deposit(sum:double+Deposit(sum:double))+Withdraw(sum:doubl+Withdraw(sum:double)e)

Class Class NameName

AttributAttributeses

(Properti(Properties and es and Fields)Fields)

OperatioOperationsns

(Method(Methods)s)

Page 11: 11 Using classes and objects

ObjectsObjects An An objectobject is a concrete is a concrete instanceinstance of a of a

particular class particular class Creating an object from a class is Creating an object from a class is

called called instantiationinstantiation Objects have stateObjects have state

Set of values associated to their Set of values associated to their attributesattributes

Example:Example: Class: Class: AccountAccount Objects: Ivan's account, Peter's accountObjects: Ivan's account, Peter's account

Page 12: 11 Using classes and objects

Objects – ExampleObjects – Example

AccountAccount

+Owner: Person+Owner: Person+Ammount: double+Ammount: double

+Suspend()+Suspend()+Deposit(sum:double+Deposit(sum:double))+Withdraw(sum:doubl+Withdraw(sum:double)e)

ClassClass ivanAccountivanAccount

+Owner="Ivan +Owner="Ivan Kolev"Kolev"+Ammount=5000.0+Ammount=5000.0

peterAccountpeterAccount

+Owner="Peter +Owner="Peter Kirov"Kirov"+Ammount=1825.33+Ammount=1825.33

kirilAccountkirilAccount

+Owner="Kiril +Owner="Kiril Kirov"Kirov"+Ammount=25.0+Ammount=25.0

ObjeObjectct

ObjeObjectct

ObjeObjectct

Page 13: 11 Using classes and objects

Classes in C#Classes in C#Using Classes and their Class Using Classes and their Class MembersMembers

Page 14: 11 Using classes and objects

Classes in C#Classes in C# Basic units that compose programsBasic units that compose programs Implementation is Implementation is encapsulatedencapsulated

(hidden) (hidden) Classes in C# can contain:Classes in C# can contain:

Fields (member variables)Fields (member variables) PropertiesProperties MethodsMethods ConstructorsConstructors Inner typesInner types Etc. (events, indexers, operators, …)Etc. (events, indexers, operators, …)

Page 15: 11 Using classes and objects

Classes in C# – Classes in C# – ExamplesExamples

Example of classes:Example of classes: System.ConsoleSystem.Console System.StringSystem.String ( (stringstring in C#) in C#) System.Int32System.Int32 ( (intint in C#) in C#) System.ArraySystem.Array System.MathSystem.Math System.Random System.Random

Page 16: 11 Using classes and objects

Declaring ObjectsDeclaring Objects

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

Instances cannot be used if they Instances cannot be used if they are are not initializednot initialized

using System;using System;......// Define two variables of type DateTime// Define two variables of type DateTimeDateTime today; DateTime today; DateTime halloween;DateTime halloween;

// Declare and initialize a structure instance// Declare and initialize a structure instanceDateTime today = DateTime.Now;DateTime today = DateTime.Now;

Page 17: 11 Using classes and objects

Fields and Fields and Properties Properties

Accessing Fields and PropertiesAccessing Fields and Properties

Page 18: 11 Using classes and objects

FieldsFields

Fields are data members of a classFields are data members of a class Can be variables and constantsCan be variables and constants Accessing a field doesn’t invoke Accessing a field doesn’t invoke

any actions of the objectany actions of the object Example:Example:

String.EmptyString.Empty (the (the """" string) string)

Page 19: 11 Using classes and objects

Accessing FieldsAccessing Fields

Constant fields can be only readConstant fields can be only read Variable fields can be read and Variable fields can be read and

modifiedmodified Usually properties are used instead Usually properties are used instead

of directly accessing variable fieldsof directly accessing variable fields Examples:Examples:

// Accessing read-only field// Accessing read-only fieldString empty = String.Empty;String empty = String.Empty;

// Accessing constant field// Accessing constant fieldint maxInt = Int32.MaxValue;int maxInt = Int32.MaxValue;

Page 20: 11 Using classes and objects

PropertiesProperties Properties look like fields (have name Properties look like fields (have name

and type), but they can contain code, and type), but they can contain code, executed when they are accessed executed when they are accessed

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

Can have two components (and at Can have two components (and at least one of them) called least one of them) called accessorsaccessors getget for reading their value for reading their value

setset for changing their value for changing their value

Page 21: 11 Using classes and objects

Properties (2)Properties (2)

According to the implemented According to the implemented accessors properties can be:accessors properties can be: Read-only (Read-only (getget accessor only) accessor only) Read and write (both Read and write (both getget and and setset

accessors)accessors) Write-only (Write-only (setset accessor only) accessor only)

Example of read-only property: Example of read-only property: String.LengthString.Length

Page 22: 11 Using classes and objects

Accessing Accessing Properties and Properties and

Fields – ExampleFields – Exampleusing System;using System;

......

DateTime christmas = new DateTime(2009, 12, DateTime christmas = new DateTime(2009, 12, 25);25);int day = christmas.Day;int day = christmas.Day;int month = christmas.Month;int month = christmas.Month;int year = christmas.Year;int year = christmas.Year;Console.WriteLine(Console.WriteLine( "Christmas day: {0}, month: {1}, year: "Christmas day: {0}, month: {1}, year: {2}",{2}", day, month, year);day, month, year);Console.WriteLine(Console.WriteLine( "Day of year: {0}", christmas.DayOfYear);"Day of year: {0}", christmas.DayOfYear);Console.WriteLine("Is {0} leap year: {1}",Console.WriteLine("Is {0} leap year: {1}", year, DateTime.IsLeapYear(year));year, DateTime.IsLeapYear(year));

Page 23: 11 Using classes and objects

Live DemoLive Demo

AccessinAccessing g

PropertiProperties and es and FieldsFields

Page 24: 11 Using classes and objects

Instance and Static Instance and Static MembersMembersAccessing Object and Class Accessing Object and Class

MembersMembers

Page 25: 11 Using classes and objects

Instance and Static Instance and Static MembersMembers

Fields, properties and methods can be:Fields, properties and methods can be: Instance (or object members)Instance (or object members) Static (or class members)Static (or class members)

Instance members are specific for each Instance members are specific for each objectobject Example: different dogs have different Example: different dogs have different

namename Static members are common for all Static members are common for all

instances of a classinstances of a class Example: Example: DateTime.MinValueDateTime.MinValue is shared is shared

between all instances of between all instances of DateTimeDateTime

Page 26: 11 Using classes and objects

Accessing Members – Accessing Members – SyntaxSyntax

Accessing instance membersAccessing instance members The name of the The name of the instanceinstance, followed , followed

by the name of the member (field or by the name of the member (field or property), separated by dot ("property), separated by dot ("..")")

Accessing static membersAccessing static members The name of the The name of the classclass, followed by , followed by

the name of the memberthe name of the member

<instance_name>.<member_name><instance_name>.<member_name>

<class_name>.<member_name><class_name>.<member_name>

Page 27: 11 Using classes and objects

Instance and Instance and Static Members Static Members

– Examples– Examples Example of instance memberExample of instance member

String.LengthString.Length Each string object has different Each string object has different

lengthlength

Example of static memberExample of static member Console.ReadLine()Console.ReadLine()

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

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

Page 28: 11 Using classes and objects

MethodsMethodsCalling Instance and Static Calling Instance and Static MethodsMethods

Page 29: 11 Using classes and objects

MethodsMethods

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

Examples:Examples: Console.WriteLine(…)Console.WriteLine(…) Console.ReadLine()Console.ReadLine() String.Substring(index, length)String.Substring(index, length) Array.GetLength(index)Array.GetLength(index)

Page 30: 11 Using classes and objects

Instance MethodsInstance Methods

Instance methods manipulate the Instance methods manipulate the data of a specified object or data of a specified object or perform any other tasksperform any other tasks If a value is returned, it depends on If a value is returned, it depends on

the particular class instancethe particular class instance Syntax:Syntax:

The name of the instance, followed The name of the instance, followed by the name of the method, by the name of the method, separated by dotseparated by dot<object_name>.<method_name>(<parameters>)<object_name>.<method_name>(<parameters>)

Page 31: 11 Using classes and objects

Calling Instance Methods – Calling Instance Methods – Examples Examples

Calling instance methods of Calling instance methods of StringString::

Calling instance methods of Calling instance methods of DateTimeDateTime::

String sampleLower = new String('a', 5);String sampleLower = new String('a', 5);String sampleUpper = sampleLower.ToUpper();String sampleUpper = sampleLower.ToUpper();

Console.WriteLine(sampleLower); // aaaaaConsole.WriteLine(sampleLower); // aaaaaConsole.WriteLine(sampleUpper); // AAAAAConsole.WriteLine(sampleUpper); // AAAAA

DateTime now = DateTime.Now;DateTime now = DateTime.Now;DateTime later = now.AddHours(8);DateTime later = now.AddHours(8);

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

Page 32: 11 Using classes and objects

Calling Instance Calling Instance MethodsMethods

Live DemoLive Demo

Page 33: 11 Using classes and objects

Static MethodsStatic Methods

Static methods are common for all Static methods are common for all instances of a class (shared instances of a class (shared between all instances)between all instances) Returned value depends only on the Returned value depends only on the

passed parameterspassed parameters No particular class instance is No particular class instance is

availableavailable Syntax:Syntax:

The name of the class, followed by The name of the class, followed by the name of the method, separated the name of the method, separated by dotby dot

<class_name>.<method_name>(<parameters>)<class_name>.<method_name>(<parameters>)

Page 34: 11 Using classes and objects

Calling Static Methods – Calling Static Methods – ExamplesExamples

using System;using System;

double radius = 2.9;double radius = 2.9;double area = Math.PI * Math.Pow(radius, 2);double area = Math.PI * Math.Pow(radius, 2);Console.WriteLine("Area: {0}", area);Console.WriteLine("Area: {0}", area);// Area: 26,4207942166902// Area: 26,4207942166902

double precise = 8.7654321;double precise = 8.7654321;double round3 = Math.Round(precise, 3);double round3 = Math.Round(precise, 3);double round1 = Math.Round(precise, 1);double round1 = Math.Round(precise, 1);Console.WriteLine(Console.WriteLine( "{0}; {1}; {2}", precise, round3, "{0}; {1}; {2}", precise, round3, round1);round1);// 8,7654321; 8,765; 8,8// 8,7654321; 8,765; 8,8

ConstaConstant fieldnt field

Static Static methometho

dd

Static Static methmeth

odod Static Static methmeth

odod

Page 35: 11 Using classes and objects

Calling Static Calling Static MethodsMethods

Live DemoLive Demo

Page 36: 11 Using classes and objects

ConstructorsConstructors Constructors are special methods Constructors are special methods

used to assign initial values of the used to assign initial values of the fields in an objectfields in an object Executed when an object of a given Executed when an object of a given

type is being createdtype is being created Have the same name as the class Have the same name as the class

that holds themthat holds them Do not return a valueDo not return a value

A class may have several A class may have several constructors with different set of constructors with different set of parametersparameters

Page 37: 11 Using classes and objects

Constructors (2)Constructors (2)

Constructor is invoked by the Constructor is invoked by the newnew operatoroperator

Examples:Examples:String s = new String("Hello!"); // s = "Hello!"String s = new String("Hello!"); // s = "Hello!"

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

String s = new String('*', 5); // s = "*****"String s = new String('*', 5); // s = "*****"

DateTime dt = new DateTime(2009, 12, 30);DateTime dt = new DateTime(2009, 12, 30);

DateTime dt = new DateTime(2009, 12, 30, 12, 33, DateTime dt = new DateTime(2009, 12, 30, 12, 33, 59);59);

Int32 value = new Int32(1024);Int32 value = new Int32(1024);

Page 38: 11 Using classes and objects

Parameterless Parameterless ConstructorsConstructors

The constructor without The constructor without parameters is called parameters is called defaultdefault constructorconstructor

Example:Example: Creating an object for generating Creating an object for generating

random numbers with a default random numbers with a default seedseed

using System;using System;......Random randomGenerator = new Random();Random randomGenerator = new Random();

The class The class System.RandomSystem.Random provides generation of provides generation of

pseudo-random numberspseudo-random numbers

ParameterlParameterless ess

constructoconstructor callr call

Page 39: 11 Using classes and objects

Constructor With Constructor With ParametersParameters

ExampleExample Creating objects for generating Creating objects for generating

random values with specified initial random values with specified initial seedsseeds

using System;using System;......Random randomGenerator1 = new Random(123);Random randomGenerator1 = new Random(123);Console.WriteLine(randomGenerator1.Next());Console.WriteLine(randomGenerator1.Next());// 2114319875// 2114319875

Random randomGenerator2 = new Random(456);Random randomGenerator2 = new Random(456);Console.WriteLine(randomGenerator2.Next(50));Console.WriteLine(randomGenerator2.Next(50));// 47// 47

Page 40: 11 Using classes and objects

Generating Random Generating Random NumbersNumbers

Live DemoLive Demo

Page 41: 11 Using classes and objects

More Constructor More Constructor ExamplesExamples

Creating a Creating a DateTimeDateTime object for a object for a specified date and timespecified date and time

Different constructors are called Different constructors are called depending on the different sets of depending on the different sets of parametersparameters

using System;using System;

DateTime halloween = new DateTime(2009, 10, DateTime halloween = new DateTime(2009, 10, 31);31);Console.WriteLine(halloween);Console.WriteLine(halloween);

DateTime julyMorning;DateTime julyMorning;julyMorning = new DateTime(2009,7,1, 5,52,0);julyMorning = new DateTime(2009,7,1, 5,52,0);Console.WriteLine(julyMorning);Console.WriteLine(julyMorning);

Page 42: 11 Using classes and objects

Creating Creating DateTimeDateTime ObjectsObjects

Live DemoLive Demo

Page 43: 11 Using classes and objects

EnumerationsEnumerationsTypes Limited to a Predefined Set of Types Limited to a Predefined Set of

ValuesValues

Page 44: 11 Using classes and objects

EnumerationsEnumerations

EnumerationsEnumerations in C# are types in C# are types whose values are limited to a whose values are limited to a predefined set of valuespredefined set of values E.g. the days of weekE.g. the days of week Declared by the keyword Declared by the keyword enumenum in C# in C# Hold values from a predefined setHold values from a predefined set

44

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

……

Color color = Color.Red;Color color = Color.Red;Console.WriteLine(color); // RedConsole.WriteLine(color); // Red

color = 5; // Compilation error!color = 5; // Compilation error!

Page 45: 11 Using classes and objects

StructuresStructuresWhat are Structures? When to Use What are Structures? When to Use

Them?Them?

Page 46: 11 Using classes and objects

StructuresStructures Structures are similar to classesStructures are similar to classes Structures are usually used for storing Structures are usually used for storing

data structures, without any other data structures, without any other functionalityfunctionality

Structures can have fields, properties, etc.Structures can have fields, properties, etc. Using methods is not recommendedUsing methods is not recommended

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

Example of structureExample of structure System.DateTimeSystem.DateTime – represents a date and – represents a date and

timetime

Page 47: 11 Using classes and objects

NamespacesNamespacesOrganizing Classes Logically into Organizing Classes Logically into

NamespacesNamespaces

Page 48: 11 Using classes and objects

What is a Namespace?What is a Namespace? Namespaces are used to organize the Namespaces are used to organize the

source code into more logical and source code into more logical and manageable waymanageable way

Namespaces can containNamespaces can contain Definitions of classes, structures, interfaces Definitions of classes, structures, interfaces

and other types and other namespacesand other types and other namespaces Namespaces can contain other namespacesNamespaces can contain other namespaces For example:For example:

SystemSystem namespace contains namespace contains DataData namespace namespace The name of the nested namespace is The name of the nested namespace is System.DataSystem.Data

Page 49: 11 Using classes and objects

Full Class NamesFull Class Names

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

Example:Example: ArrayArray class, defined in the class, defined in the SystemSystem

namespacenamespace The full name of the class is The full name of the class is System.ArraySystem.Array

<namespace_name>.<class_name><namespace_name>.<class_name>

Page 50: 11 Using classes and objects

Including NamespacesIncluding Namespaces

The The usingusing directive in C#: directive in C#:

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

Example:Example:

instead ofinstead of

using <namespace_name>using <namespace_name>

using System;using System;DateTime date;DateTime date;

System.DateTime date;System.DateTime date;

Page 51: 11 Using classes and objects

Random Random ClassClass

Password Generator Password Generator DemoDemo

51

Page 52: 11 Using classes and objects

The The RandomRandom Class Class The The RandomRandom classclass

Generates random integer numbersGenerates random integer numbers bytebyte or or intint

Random rand = new Random();Random rand = new Random();for (int number = 1; number <= 6; number++)for (int number = 1; number <= 6; number++){{ iint randomNumber = rand.Next(49) + 1;nt randomNumber = rand.Next(49) + 1; Console.Write("{0} ", randomNumber);Console.Write("{0} ", randomNumber);}}

This generates six random This generates six random numbers from 1 to 49numbers from 1 to 49

The The Next()Next() method returns a method returns a random numberrandom number

Page 53: 11 Using classes and objects

Password GeneratorPassword Generator Generates a random password between 8 Generates a random password between 8

and 15 charactersand 15 characters The password contains of at least two capital The password contains of at least two capital

letters, two small letters, one digit and three letters, two small letters, one digit and three special charactersspecial characters

Constructing the Password Generator Constructing the Password Generator class:class: Start from empty passwordStart from empty password Place two random capital letters at random Place two random capital letters at random

positionspositions Place two random small letters at random Place two random small letters at random

positionspositions Place one random digit at random positionsPlace one random digit at random positions Place three special characters at random Place three special characters at random

positionspositions 53

Page 54: 11 Using classes and objects

Password Generator (2)Password Generator (2) Now we have exactly 8 charactersNow we have exactly 8 characters

To make the length between 8 and 15 To make the length between 8 and 15 we generate a number N between 0 and we generate a number N between 0 and 77

And then inserts N random characters And then inserts N random characters ( capital letter or small letter or digit or ( capital letter or small letter or digit or special character) at random positionsspecial character) at random positions

54

Page 55: 11 Using classes and objects

class RandomPasswordGeneratorclass RandomPasswordGenerator{{ private const string private const string CapitalLettersCapitalLetters== "ABCDEFGHIJKLMNOPQRSTUVWXYZ";"ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private const string private const string SmallLettersSmallLetters = = "abcdefghijklmnopqrstuvwxyz";"abcdefghijklmnopqrstuvwxyz"; private const string private const string DigitsDigits = "0123456789"; = "0123456789"; pprivate const string rivate const string SpecialCharsSpecialChars = = "~!@#$%^&*()_+=`{}[]\\|':;.,/?<>";"~!@#$%^&*()_+=`{}[]\\|':;.,/?<>"; private const string private const string AllCharsAllChars = = CapitalLettersCapitalLetters + + SmallLetters SmallLetters + + Digits Digits + + SpecialCharsSpecialChars;; private static Random rnd = new Random();private static Random rnd = new Random();

  // the example continues…// the example continues…

Password Generator Password Generator ClassClass

Page 56: 11 Using classes and objects

Password Generator Password Generator ClassClass

56

static void Main()static void Main(){{ StringBuilder password = new StringBuilder();StringBuilder password = new StringBuilder(); ffor (int i = 1; i <= 2; i++)or (int i = 1; i <= 2; i++) {{ char capitalLetter = GenerateChar(char capitalLetter = GenerateChar(CapitalLettersCapitalLetters);); InsertAtRandomPosition(password, capitalLetter);InsertAtRandomPosition(password, capitalLetter); }} for (int i = 1; i <= 2; i++)for (int i = 1; i <= 2; i++) {{ char smallLetter = GenerateChar(char smallLetter = GenerateChar(SmallLettersSmallLetters);); InsertAtRandomPosition(password, smallLetter);InsertAtRandomPosition(password, smallLetter); }} char digit = GenerateChar(char digit = GenerateChar(DigitsDigits);); InsertAtRandomPosition(password, digit);InsertAtRandomPosition(password, digit); for (int i = 1; i <= 3; i++)for (int i = 1; i <= 3; i++) {{ char specialChar = GenerateChar(char specialChar = GenerateChar(SpecialCharsSpecialChars);); InsertAtRandomPosition(password, specialChar);InsertAtRandomPosition(password, specialChar); } } // the example continues…// the example continues…

Page 57: 11 Using classes and objects

Password Generator Password Generator ClassClass

57

int count = rnd.Next(8);int count = rnd.Next(8); for (int i = 1; i <= count; i++)for (int i = 1; i <= count; i++) {{ char specialChar = GenerateChar(char specialChar = GenerateChar(AllCharsAllChars);); InsertAtRandomPosition(password, specialChar);InsertAtRandomPosition(password, specialChar); } }  Console.WriteLine(password);Console.WriteLine(password);}}

private static void InsertAtRandomPosition(private static void InsertAtRandomPosition( StringBuilder password, char character)StringBuilder password, char character){{ int randomPosition = rnd.Next(password.Length + 1);int randomPosition = rnd.Next(password.Length + 1); password.Insert(randomPosition, character);password.Insert(randomPosition, character);}}

private static char GenerateChar(string availableChars)private static char GenerateChar(string availableChars){{ iint randomIndex = rnd.Next(availableChars.Length);nt randomIndex = rnd.Next(availableChars.Length); char randomChar = availableChars[randomIndex];char randomChar = availableChars[randomIndex]; return randomChar;return randomChar;}}

Page 58: 11 Using classes and objects

.NET Common Type .NET Common Type SystemSystem

Brief IntroductionBrief Introduction

Page 59: 11 Using classes and objects

Common Type System Common Type System (CTS)(CTS)

CTS defines all data CTS defines all data typestypes supported in .NET Frameworksupported in .NET Framework Primitive types (e.g. Primitive types (e.g. intint, , floatfloat, , objectobject))

Classes (e.g. Classes (e.g. StringString, , ConsoleConsole, , ArrayArray)) Structures (e.g. Structures (e.g. DateTimeDateTime)) Arrays (e.g. Arrays (e.g. intint[][], , string[,]string[,])) Etc.Etc.

Object-oriented by designObject-oriented by design

Page 60: 11 Using classes and objects

CTS and Different CTS and Different LanguagesLanguages

CTS is common for all .NET CTS is common for all .NET languageslanguages C#, VB.NET, J#, C#, VB.NET, J#, JScript.NETJScript.NET, ..., ...

CTS type mappings:CTS type mappings:CTS TypeCTS Type C# TypeC# Type VB.NET TypeVB.NET Type

System.Int32System.Int32 intint IntegerInteger

System.SingleSystem.Single floatfloat SingleSingle

System.BooleanSystem.Boolean boolbool BooleanBoolean

System.StringSystem.String stringstring StringString

System.ObjectSystem.Object objectobject ObjectObject

Page 61: 11 Using classes and objects

Value and Reference Value and Reference TypesTypes

In CTS there are two categories of In CTS there are two categories of typestypes ValueValue typestypes Reference typesReference types

Placed in different areas of memoryPlaced in different areas of memory Value types live in the Value types live in the execution stackexecution stack

Freed when become out of scopeFreed when become out of scope

Reference types live in the Reference types live in the managed managed heap heap (dynamic memory)(dynamic memory) Freed by the Freed by the garbage collectorgarbage collector

Page 62: 11 Using classes and objects

Value and Reference Value and Reference Types – ExamplesTypes – Examples

Value typesValue types Most of the primitive typesMost of the primitive types StructuresStructures Examples: Examples: intint, , floatfloat, , boolbool, , DateTimeDateTime

Reference typesReference types Classes and interfacesClasses and interfaces StringsStrings ArraysArrays Examples: Examples: stringstring, , RandomRandom, , objectobject, , int[]int[]

Page 63: 11 Using classes and objects

System.Object: CTS System.Object: CTS Base TypeBase Type

System.ObjectSystem.Object ( (objectobject in C#) is a in C#) is a base base type type for all other typesfor all other types in CTS in CTS Can hold values of any other type:Can hold values of any other type:

All .NET types derive common All .NET types derive common methods from methods from System.ObjectSystem.Object, e.g. , e.g. ToString()ToString()

string s = "test";string s = "test";object obj = s;object obj = s;

DateTime now = DateTime.Now;DateTime now = DateTime.Now;string nowInWords = now.ToString();string nowInWords = now.ToString();Console.WriteLine(nowInWords);Console.WriteLine(nowInWords);

Page 64: 11 Using classes and objects

SummarySummary

Classes provide the structure for Classes provide the structure for objectsobjects

Objects are particular instances of Objects are particular instances of classesclasses

Classes have different membersClasses have different members Methods, fields, properties, etc.Methods, fields, properties, etc. Instance and static membersInstance and static members Members can be accessedMembers can be accessed Methods can be calledMethods can be called

Structures are used for storing dataStructures are used for storing data

Page 65: 11 Using classes and objects

Summary (2)Summary (2) Namespaces help organizing the Namespaces help organizing the

classesclasses

Common Type System (CTS) Common Type System (CTS) defines the types for all .NET defines the types for all .NET languageslanguages

Values typesValues types

Reference typesReference types

Page 66: 11 Using classes and objects

QuestionsQuestions??

Using Classes and Using Classes and ObjectsObjects

http://academy.telerik.com

Page 67: 11 Using classes and objects

ExercisesExercises1.1. Write a program that reads a year from the Write a program that reads a year from the

console and checks whether it is a leap. Use console and checks whether it is a leap. Use DateTimeDateTime..

2.2. Write a program that generates and prints to the Write a program that generates and prints to the console 10 random values in the range [100, console 10 random values in the range [100, 200].200].

3.3. Write a program that prints to the console which Write a program that prints to the console which day of the week is today. Use day of the week is today. Use System.DateTimeSystem.DateTime..

4.4. Write methods that calculate the surface of a Write methods that calculate the surface of a triangle by given:triangle by given:

Side and an altitude to it; Three sides; Two Side and an altitude to it; Three sides; Two sides and an angle between them. Use sides and an angle between them. Use System.MathSystem.Math..

Page 68: 11 Using classes and objects

Exercises (2)Exercises (2)

5.5. Write a method that calculates the number Write a method that calculates the number of workdays between today and given date, of workdays between today and given date, passed as parameter. Consider that passed as parameter. Consider that workdays are all days from Monday to workdays are all days from Monday to Friday except a fixed array of public Friday except a fixed array of public holidays specified preliminary as array.holidays specified preliminary as array.

6.6. You are given a sequence of positive integer You are given a sequence of positive integer values written into a string, separated by values written into a string, separated by spaces. Write a function that reads these spaces. Write a function that reads these values from given string and calculates values from given string and calculates their sum. Example:their sum. Example:

string = "string = "43 68 9 23 31843 68 9 23 318" " result = result = 461461

Page 69: 11 Using classes and objects

Exercises (3)Exercises (3)7.7. * Write a program that calculates the value of * Write a program that calculates the value of

given arithmetical expression. The expression given arithmetical expression. The expression can contain the following elements only:can contain the following elements only:

Real numbers, e.g. Real numbers, e.g. 55, , 18.3318.33, , 3.141593.14159, , 12.612.6 Arithmetic operators: Arithmetic operators: ++, , --, , **, , // (standard (standard

priorities)priorities) Mathematical functions: Mathematical functions: ln(x)ln(x), , sqrt(x)sqrt(x), , pow(x,y)pow(x,y) Brackets (for changing the default priorities)Brackets (for changing the default priorities)

Examples:Examples:(3+5.3)(3+5.3) ** 2.72.7 -- ln(22)ln(22) // pow(2.2,pow(2.2, -1.7)-1.7) ~~ 10.610.6

pow(2,pow(2, 3.14)3.14) ** (3(3 -- (3(3 ** sqrt(2)sqrt(2) -- 3.2)3.2) ++ 1.5*0.3)1.5*0.3) ~ 21.22~ 21.22

Hint: Use the classical Hint: Use the classical "shunting yard" algorithm and and "reverse Polish notation"..