SlideShare a Scribd company logo
Using Classes and ObjectsUsing Classes and Objects
Using the Standard .NET Framework ClassesUsing the Standard .NET Framework Classes
Svetlin NakovSvetlin Nakov
Telerik CorporationTelerik Corporation
www.telerik.comwww.telerik.com
Table of ContentsTable of Contents
1.1. Classes and ObjectsClasses and Objects
What are Objects?What are Objects?
What are Classes?What are Classes?
1.1. Classes in C#Classes in C#
Declaring ClassDeclaring Class
Fields and Properties: Instance and StaticFields and Properties: Instance and Static
Instance and Static MethodsInstance and Static Methods
ConstructorsConstructors
1.1. StructuresStructures
Table of Contents (2)Table of Contents (2)
4.4. NamespacesNamespaces
5.5. RandomRandom classclass
6.6. Introduction to .NETIntroduction to .NET
Common Type SystemCommon Type System
Classes and ObjectsClasses and Objects
Modeling Real-world Entities with ObjectsModeling Real-world Entities with Objects
What are Objects?What are Objects?
 Software objects model real-world objects orSoftware objects model real-world objects or
abstract conceptsabstract concepts
Examples:Examples:
 bank, account, customer, dog, bicycle, queuebank, account, customer, dog, bicycle, queue
 Real-world objects haveReal-world objects have statesstates andand behaviorsbehaviors
Account' states:Account' states:
 holder, balance, typeholder, balance, type
Account' behaviors:Account' behaviors:
 withdraw, deposit, suspendwithdraw, deposit, suspend
What are Objects? (2)What are Objects? (2)
 How do software objects implement real-How do software objects implement real-
world objects?world objects?
Use variables/data to implement statesUse variables/data to implement states
Use methods/functions to implement behaviorsUse methods/functions to implement behaviors
 An object is a software bundle of variables andAn object is a software bundle of variables and
related methodsrelated methods
Objects RepresentObjects Represent
7
checkschecks
peoplepeople
shopping listshopping list
……
numbersnumbers
characterscharacters
queuesqueues
arraysarrays
Things fromThings from
the real worldthe real world
Things from theThings from the
computer worldcomputer world
What is Class?What is Class?
 The formal definition ofThe formal definition of classclass::
Definition by GoogleDefinition by Google
ClassesClasses act as templates from which anact as templates from which an
instance of an object is created at runinstance of an object is created at run
time. Classes define the properties of thetime. Classes define the properties of the
object and the methods used to controlobject and the methods used to control
the object's behavior.the object's behavior.
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 ofSet of attributesattributes
 Represented by variables and propertiesRepresented by variables and properties
 Hold theirHold their statestate
Set of actions (Set of actions (behaviorbehavior))
 Represented by methodsRepresented by methods
 A class defines the methods and types of dataA class defines the methods and types of data
associated with an objectassociated with an object
Classes – ExampleClasses – Example
AccountAccount
+Owner: Person+Owner: Person
+Ammount: double+Ammount: double
+Suspend()+Suspend()
+Deposit(sum:double)+Deposit(sum:double)
+Withdraw(sum:double)+Withdraw(sum:double)
ClassClass
NameName
AttributesAttributes
(Properties(Properties
and Fields)and Fields)
OperationsOperations
(Methods)(Methods)
ObjectsObjects
 AnAn objectobject is a concreteis a concrete instanceinstance of a particularof a particular
classclass
 Creating an object from a class is calledCreating an object from a class is called
instantiationinstantiation
 Objects have stateObjects have state
Set of values associated to their attributesSet of values associated to their attributes
 Example:Example:
Class:Class: AccountAccount
Objects: Ivan's account, Peter's accountObjects: Ivan's account, Peter's account
Objects – ExampleObjects – Example
AccountAccount
+Owner: Person+Owner: Person
+Ammount: double+Ammount: double
+Suspend()+Suspend()
+Deposit(sum:double)+Deposit(sum:double)
+Withdraw(sum:double)+Withdraw(sum:double)
ClassClass ivanAccountivanAccount
+Owner="Ivan Kolev"+Owner="Ivan Kolev"
+Ammount=5000.0+Ammount=5000.0
peterAccountpeterAccount
+Owner="Peter Kirov"+Owner="Peter Kirov"
+Ammount=1825.33+Ammount=1825.33
kirilAccountkirilAccount
+Owner="Kiril Kirov"+Owner="Kiril Kirov"
+Ammount=25.0+Ammount=25.0
ObjectObject
ObjectObject
ObjectObject
Classes in C#Classes in C#
Using Classes and their Class MembersUsing Classes and their Class Members
Classes in C#Classes in C#
 Basic units that compose programsBasic units that compose programs
 Implementation isImplementation 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, …)
Classes in C# – ExamplesClasses in C# – Examples
 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.RandomSystem.Random
Declaring ObjectsDeclaring Objects
 An instance of a class or structure can beAn instance of a class or structure can be
defined like any other variable:defined like any other variable:
 Instances cannot be used if they areInstances cannot be used if they are
not initializednot initialized
using System;using System;
......
// Define two variables of type DateTime// Define two variables of type DateTime
DateTime today;DateTime today;
DateTime halloween;DateTime halloween;
// Declare and initialize a structure instance// Declare and initialize a structure instance
DateTime today = DateTime.Now;DateTime today = DateTime.Now;
Fields and PropertiesFields and Properties
Accessing Fields and PropertiesAccessing Fields and Properties
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 any actions ofAccessing a field doesn’t invoke any actions of
the objectthe object
 Example:Example:
String.EmptyString.Empty (the(the """" string)string)
Accessing FieldsAccessing Fields
 Constant fields can be only readConstant fields can be only read
 Variable fields can be read and modifiedVariable fields can be read and modified
 Usually properties are used instead of directlyUsually properties are used instead of directly
accessing variable fieldsaccessing variable fields
 Examples:Examples:
// Accessing read-only field// Accessing read-only field
String empty = String.Empty;String empty = String.Empty;
// Accessing constant field// Accessing constant field
int maxInt = Int32.MaxValue;int maxInt = Int32.MaxValue;
PropertiesProperties
 Properties look like fields (have name andProperties look like fields (have name and
type), but they can contain code, executedtype), but they can contain code, executed
when they are accessedwhen they are accessed
 Usually used to control access to dataUsually used to control access to data
fields (wrappers), but can contain morefields (wrappers), but can contain more
complex logiccomplex logic
 Can have two components (and at least oneCan have two components (and at least one
of them) calledof them) called accessorsaccessors
 getget for reading their valuefor reading their value
 setset for changing their valuefor changing their value
Properties (2)Properties (2)
 According to the implemented accessorsAccording to the implemented accessors
properties can be:properties can be:
Read-only (Read-only (getget accessor only)accessor only)
Read and write (bothRead and write (both getget andand 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
Accessing PropertiesAccessing Properties
and Fields – Exampleand Fields – Example
using System;using System;
......
DateTime christmas = new DateTime(2009, 12, 25);DateTime christmas = new DateTime(2009, 12, 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: {2}","Christmas day: {0}, month: {1}, year: {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));
Live DemoLive Demo
AccessingAccessing
PropertiesProperties
and Fieldsand Fields
Instance and Static MembersInstance and Static Members
Accessing Object and Class MembersAccessing Object and Class Members
Instance and Static MembersInstance and Static Members
 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 objectInstance members are specific for each object
Example: different dogs have different nameExample: different dogs have different name
 Static members are common for all instancesStatic members are common for all instances
of a classof a class
Example:Example: DateTime.MinValueDateTime.MinValue is sharedis shared
between all instances ofbetween all instances of DateTimeDateTime
Accessing Members – SyntaxAccessing Members – Syntax
 Accessing instance membersAccessing instance members
The name of theThe name of the instanceinstance, followed by the, followed by the
name of the member (field or property),name of the member (field or property),
separated by dot ("separated by dot ("..")")
 Accessing static membersAccessing static members
The name of theThe name of the classclass, followed by the name of, followed by the name of
the memberthe member
<instance_name>.<member_name><instance_name>.<member_name>
<class_name>.<member_name><class_name>.<member_name>
Instance and StaticInstance and Static
Members – ExamplesMembers – Examples
 Example of instance memberExample of instance member
 String.LengthString.Length
 Each string object has different lengthEach string object has different length
 Example of static memberExample of static member
 Console.ReadLine()Console.ReadLine()
 The console is only one (global for the program)The console is only one (global for the program)
 Reading from the console does not require toReading from the console does not require to
create an instance of itcreate an instance of it
MethodsMethods
Calling Instance and Static MethodsCalling Instance and Static Methods
MethodsMethods
 Methods manipulate the data of the object toMethods manipulate the data of the object to
which they belong or perform other taskswhich they belong or perform 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)
Instance MethodsInstance Methods
 Instance methods manipulate the data of aInstance methods manipulate the data of a
specified object or perform any other tasksspecified object or perform any other tasks
If a value is returned, it depends on theIf a value is returned, it depends on the
particular class instanceparticular class instance
 Syntax:Syntax:
The name of the instance, followed by theThe name of the instance, followed by the
name of the method, separated by dotname of the method, separated by dot
<object_name>.<method_name>(<parameters>)<object_name>.<method_name>(<parameters>)
Calling Instance Methods –Calling Instance Methods –
ExamplesExamples
 Calling instance methods ofCalling instance methods of StringString::
 Calling instance methods ofCalling 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); // aaaaa
Console.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}", later);Console.WriteLine("8 hours later: {0}", later);
Calling Instance MethodsCalling Instance Methods
Live DemoLive Demo
Static MethodsStatic Methods
 Static methods are common for all instances ofStatic methods are common for all instances of
a class (shared between all instances)a class (shared between all instances)
Returned value depends only on the passedReturned value depends only on the passed
parametersparameters
No particular class instance is availableNo particular class instance is available
 Syntax:Syntax:
The name of the class, followed by the name ofThe name of the class, followed by the name of
the method, separated by dotthe method, separated by dot
<class_name>.<method_name>(<parameters>)<class_name>.<method_name>(<parameters>)
Calling Static Methods – ExamplesCalling Static Methods – Examples
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, round1);"{0}; {1}; {2}", precise, round3, round1);
// 8,7654321; 8,765; 8,8// 8,7654321; 8,765; 8,8
ConstantConstant
fieldfield
StaticStatic
methodmethod
StaticStatic
methometho
dd StaticStatic
methometho
dd
Calling Static MethodsCalling Static Methods
Live DemoLive Demo
ConstructorsConstructors
 Constructors are special methods used toConstructors are special methods used to
assign initial values of the fields in an objectassign initial values of the fields in an object
Executed when an object of a given type isExecuted when an object of a given type is
being createdbeing created
Have the same name as the class that holdsHave the same name as the class that holds
themthem
Do not return a valueDo not return a value
 A class may have several constructors withA class may have several constructors with
different set of parametersdifferent set of parameters
Constructors (2)Constructors (2)
 Constructor is invoked by theConstructor 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, 59);DateTime dt = new DateTime(2009, 12, 30, 12, 33, 59);
Int32 value = new Int32(1024);Int32 value = new Int32(1024);
Parameterless ConstructorsParameterless Constructors
 The constructor without parameters is calledThe constructor without parameters is called
defaultdefault constructorconstructor
 Example:Example:
Creating an object for generating randomCreating an object for generating random
numbers with a default seednumbers with a default seed
using System;using System;
......
Random randomGenerator = new Random();Random randomGenerator = new Random();
The classThe class System.RandomSystem.Random providesprovides
generation of pseudo-randomgeneration of pseudo-random
numbersnumbers
ParameterlessParameterless
constructorconstructor
callcall
Constructor With ParametersConstructor With Parameters
 ExampleExample
Creating objects for generating random valuesCreating objects for generating random values
with specified initial seedswith specified initial seeds
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
Generating Random NumbersGenerating Random Numbers
Live DemoLive Demo
More Constructor ExamplesMore Constructor Examples
 Creating aCreating a DateTimeDateTime object for a specifiedobject for a specified
date and timedate and time
 Different constructors are called depending onDifferent constructors are called depending on
the different sets of parametersthe different sets of parameters
using System;using System;
DateTime halloween = new DateTime(2009, 10, 31);DateTime halloween = new DateTime(2009, 10, 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);
CreatingCreating DateTimeDateTime ObjectsObjects
Live DemoLive Demo
EnumerationsEnumerations
Types Limited to a Predefined Set ofValuesTypes Limited to a Predefined Set ofValues
EnumerationsEnumerations
 EnumerationsEnumerations in C# are types whose values arein C# are types whose values are
limited to a predefined set of valueslimited to a predefined set of values
E.g. the days of weekE.g. the days of week
Declared by the keywordDeclared 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!
StructuresStructures
What are Structures? When to Use Them?What are Structures? When to Use Them?
StructuresStructures
 Structures are similar to classesStructures are similar to classes
 Structures are usually used for storing dataStructures are usually used for storing data
structures, without any other functionalitystructures, without any other functionality
 Structures can have fields, properties, etc.Structures can have fields, properties, etc.
Using methods is not recommendedUsing methods is not recommended
 Structures areStructures are value typesvalue types, and classes are, and classes are
reference typesreference types (this will be discussed later)(this will be discussed later)
 Example of structureExample of structure
System.DateTimeSystem.DateTime – represents a date and time– represents a date and time
NamespacesNamespaces
Organizing Classes Logically into NamespacesOrganizing Classes Logically into Namespaces
What is a Namespace?What is a Namespace?
 Namespaces are used to organize the sourceNamespaces are used to organize the source
code into more logical and manageable waycode into more logical and manageable way
 Namespaces can containNamespaces can contain
Definitions of classes, structures, interfaces andDefinitions of classes, structures, interfaces and
other types and other namespacesother types and other namespaces
 Namespaces can contain other namespacesNamespaces can contain other namespaces
 For example:For example:
SystemSystem namespace containsnamespace contains DataData namespacenamespace
The name of the nested namespace isThe name of the nested namespace is
System.DataSystem.Data
Full Class NamesFull Class Names
 A full name of a class is the name of the classA full name of a class is the name of the class
preceded by the name of its namespacepreceded by the name of its namespace
 Example:Example:
ArrayArray class, defined in theclass, defined in the SystemSystem namespacenamespace
The full name of the class isThe full name of the class is System.ArraySystem.Array
<namespace_name>.<class_name><namespace_name>.<class_name>
Including NamespacesIncluding Namespaces
 TheThe usingusing directive in C#:directive in C#:
 Allows using types in a namespace, withoutAllows using types in a namespace, without
specifying their full namespecifying 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;
Random ClassRandom Class
Password Generator DemoPassword Generator Demo
51
TheThe RandomRandom ClassClass
 TheThe RandomRandom classclass
Generates random integer numbersGenerates random integer numbers
 bytebyte oror 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 numbers from 1 toThis generates six random numbers from 1 to
4949
 TheThe Next()Next() method returns a randommethod returns a random
numbernumber
Password GeneratorPassword Generator
 Generates a random password between 8 and 15Generates a random password between 8 and 15
characterscharacters
 The password contains of at least two capitalThe password contains of at least two capital
letters, two small letters, one digit and threeletters, two small letters, one digit and three
special charactersspecial characters
 Constructing the Password Generator class:Constructing the Password Generator class:
 Start from empty passwordStart from empty password
 Place two random capital letters at randomPlace two random capital letters at random
positionspositions
 Place two random small letters at random positionsPlace two random small letters at random positions
 Place one random digit at random positionsPlace one random digit at random positions
 Place three special characters at random positionsPlace three special characters at random positions
53
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 weTo make the length between 8 and 15 we
generate a number N between 0 and 7generate a number N between 0 and 7
And then inserts N random characters ( capitalAnd then inserts N random characters ( capital
letter or small letter or digit or specialletter or small letter or digit or special
character) at random positionscharacter) at random positions
54
class RandomPasswordGeneratorclass RandomPasswordGenerator
{{
private const stringprivate const string CapitalLettersCapitalLetters==
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private const stringprivate const string SmallLettersSmallLetters ==
"abcdefghijklmnopqrstuvwxyz";"abcdefghijklmnopqrstuvwxyz";
private const stringprivate const string DigitsDigits = "0123456789";= "0123456789";
pprivate const stringrivate const string SpecialCharsSpecialChars ==
"~!@#$%^&*()_+=`{}[]|':;.,/?<>";"~!@#$%^&*()_+=`{}[]|':;.,/?<>";
private const stringprivate const string AllCharsAllChars ==
CapitalLettersCapitalLetters ++ SmallLettersSmallLetters ++ DigitsDigits ++ SpecialCharsSpecialChars;;
private static Random rnd = new Random();private static Random rnd = new Random();
// the example continues…// the example continues…
Password Generator ClassPassword Generator Class
Password Generator ClassPassword Generator Class
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…
Password Generator ClassPassword Generator Class
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;
}}
.NET CommonType System.NET CommonType System
Brief IntroductionBrief Introduction
Common Type System (CTS)Common Type System (CTS)
 CTS defines all dataCTS defines all data typestypes supported in .NETsupported in .NET
FrameworkFramework
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
CTS and Different LanguagesCTS and Different Languages
 CTS is common for all .NET languagesCTS is common for all .NET languages
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
Value and Reference TypesValue and Reference Types
 In CTS there are two categories of typesIn CTS there are two categories of types
ValueValue typestypes
Reference typesReference types
 Placed in different areas of memoryPlaced in different areas of memory
Value types live in theValue types live in the execution stackexecution stack
 Freed when become out of scopeFreed when become out of scope
Reference types live in theReference types live in the managed heapmanaged heap
(dynamic memory)(dynamic memory)
 Freed by theFreed by the garbage collectorgarbage collector
Value and Reference Types –Value and Reference Types –
ExamplesExamples
 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[]
System.Object: CTS Base TypeSystem.Object: CTS Base Type
 System.ObjectSystem.Object ((objectobject in C#) is a basein C#) is a base typetype
for all other typesfor all other types in CTSin CTS
Can hold values of any other type:Can hold values of any other type:
 All .NET types derive common methods fromAll .NET types derive common 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);
SummarySummary
 Classes provide the structure for objectsClasses provide the structure for objects
 Objects are particular instances of classesObjects are particular instances of classes
 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
Summary (2)Summary (2)
 Namespaces help organizing the classesNamespaces help organizing the classes
 Common Type System (CTS) defines the typesCommon Type System (CTS) defines the types
for all .NET languagesfor all .NET languages
Values typesValues types
Reference typesReference types
Questions?Questions?
Using Classes and ObjectsUsing Classes and Objects
http://academy.telerik.com
ExercisesExercises
1.1. Write a program that reads a year from the consoleWrite a program that reads a year from the console
and checks whether it is a leap. Useand checks whether it is a leap. Use DateTimeDateTime..
2.2. Write a program that generates and prints to theWrite a program that generates and prints to the
console 10 random values in the range [100, 200].console 10 random values in the range [100, 200].
3.3. Write a program that prints to the console which dayWrite a program that prints to the console which day
of the week is today. Useof the week is today. Use System.DateTimeSystem.DateTime..
4.4. Write methods that calculate the surface of a triangleWrite methods that calculate the surface of a triangle
by given:by given:
 Side and an altitude to it; Three sides; Two sidesSide and an altitude to it; Three sides; Two sides
and an angle between them. Useand an angle between them. Use System.MathSystem.Math..
Exercises (2)Exercises (2)
5.5. Write a method that calculates the number ofWrite a method that calculates the number of
workdays between today and given date, passed asworkdays between today and given date, passed as
parameter. Consider that workdays are all days fromparameter. Consider that workdays are all days from
Monday to Friday except a fixed array of publicMonday to 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 valuesYou are given a sequence of positive integer values
written into a string, separated by spaces. Write awritten into a string, separated by spaces. Write a
function that reads these values from given stringfunction that reads these values from given string
and calculates their sum. Example:and calculates their sum. Example:
string = "string = "43 68 9 23 31843 68 9 23 318""  result =result = 461461
Exercises (3)Exercises (3)
7.7. * Write a program that calculates the value of given* Write a program that calculates the value of given
arithmetical expression. The expression can containarithmetical expression. The expression can contain
the following elements only: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 priorities)(standard 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 classicalHint: Use the classical "shunting yard" algorithm"shunting yard" algorithm andand
"reverse Polish notation""reverse Polish notation"..

More Related Content

What's hot

Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
mcollison
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
ITFT-Classes and object in java
ITFT-Classes and object in javaITFT-Classes and object in java
ITFT-Classes and object in java
Atul Sehdev
 
Classes&amp;objects
Classes&amp;objectsClasses&amp;objects
Classes&amp;objects
M Vishnuvardhan Reddy
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Classes and objects in java
Classes and objects in javaClasses and objects in java
Classes and objects in java
Muthukumaran Subramanian
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using Java
Glenn Guden
 
Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1 Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1
Sakthi Durai
 
Class or Object
Class or ObjectClass or Object
Class or Object
Rahul Bathri
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
Vinod Kumar
 
4 Classes & Objects
4 Classes & Objects4 Classes & Objects
4 Classes & Objects
Praveen M Jigajinni
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
Lokesh Kakkar Mobile No. 814-614-5674
 
Oops in java
Oops in javaOops in java
Oop java
Oop javaOop java
Oop java
Minal Maniar
 
Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...
JAINAM KAPADIYA
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
Praveen M Jigajinni
 
C++ classes
C++ classesC++ classes
C++ classes
imhammadali
 
Week9 Intro to classes and objects in Java
Week9 Intro to classes and objects in JavaWeek9 Intro to classes and objects in Java
Week9 Intro to classes and objects in Java
kjkleindorfer
 

What's hot (20)

Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
ITFT-Classes and object in java
ITFT-Classes and object in javaITFT-Classes and object in java
ITFT-Classes and object in java
 
Classes&amp;objects
Classes&amp;objectsClasses&amp;objects
Classes&amp;objects
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Classes and objects in java
Classes and objects in javaClasses and objects in java
Classes and objects in java
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using Java
 
Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1 Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1
 
Class or Object
Class or ObjectClass or Object
Class or Object
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
4 Classes & Objects
4 Classes & Objects4 Classes & Objects
4 Classes & Objects
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
 
Oops Concept Java
Oops Concept JavaOops Concept Java
Oops Concept Java
 
Oops in java
Oops in javaOops in java
Oops in java
 
Oop java
Oop javaOop java
Oop java
 
Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
C++ classes
C++ classesC++ classes
C++ classes
 
Week9 Intro to classes and objects in Java
Week9 Intro to classes and objects in JavaWeek9 Intro to classes and objects in Java
Week9 Intro to classes and objects in Java
 

Viewers also liked

classes & objects introduction
classes & objects introductionclasses & objects introduction
classes & objects introduction
Kumar
 
LAFS Game Design 1 - Structural Elements
LAFS Game Design 1 - Structural ElementsLAFS Game Design 1 - Structural Elements
LAFS Game Design 1 - Structural Elements
David Mullich
 
Introduction To Uml
Introduction To UmlIntroduction To Uml
Introduction To Umlguest514814
 
Class and object_diagram
Class  and object_diagramClass  and object_diagram
Class and object_diagramSadhana28
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
Pooja Jaiswal
 
UML- Unified Modeling Language
UML- Unified Modeling LanguageUML- Unified Modeling Language
UML- Unified Modeling Language
Shahzad
 
UML Diagrams
UML DiagramsUML Diagrams
UML Diagrams
Kartik Raghuvanshi
 
Uml diagrams
Uml diagramsUml diagrams
Uml diagrams
barney92
 
Structured Vs, Object Oriented Analysis and Design
Structured Vs, Object Oriented Analysis and DesignStructured Vs, Object Oriented Analysis and Design
Structured Vs, Object Oriented Analysis and Design
Motaz Saad
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Conceptsthinkphp
 

Viewers also liked (10)

classes & objects introduction
classes & objects introductionclasses & objects introduction
classes & objects introduction
 
LAFS Game Design 1 - Structural Elements
LAFS Game Design 1 - Structural ElementsLAFS Game Design 1 - Structural Elements
LAFS Game Design 1 - Structural Elements
 
Introduction To Uml
Introduction To UmlIntroduction To Uml
Introduction To Uml
 
Class and object_diagram
Class  and object_diagramClass  and object_diagram
Class and object_diagram
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
UML- Unified Modeling Language
UML- Unified Modeling LanguageUML- Unified Modeling Language
UML- Unified Modeling Language
 
UML Diagrams
UML DiagramsUML Diagrams
UML Diagrams
 
Uml diagrams
Uml diagramsUml diagrams
Uml diagrams
 
Structured Vs, Object Oriented Analysis and Design
Structured Vs, Object Oriented Analysis and DesignStructured Vs, Object Oriented Analysis and Design
Structured Vs, Object Oriented Analysis and Design
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 

Similar to Using class and object java

C# Language Overview Part II
C# Language Overview Part IIC# Language Overview Part II
C# Language Overview Part IIDoncho Minkov
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptclassandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.ppt
manomkpsg
 
5. c sharp language overview part ii
5. c sharp language overview   part ii5. c sharp language overview   part ii
5. c sharp language overview part iiSvetlin Nakov
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
ssuser8347a1
 
oops-1
oops-1oops-1
oops-1
snehaarao19
 
Object oriented programming tutorial
Object oriented programming tutorialObject oriented programming tutorial
Object oriented programming tutorial
Ghulam Abbas Khan
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .Net
Greg Sohl
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects newlykado0dles
 
Reflection in C#
Reflection in C#Reflection in C#
Reflection in C#
Rohit Vipin Mathews
 
07slide.ppt
07slide.ppt07slide.ppt
07slide.ppt
NuurAxmed2
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
Madishetty Prathibha
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programming
Neelesh Shukla
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
madhavi patil
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
Java Unit 2(Part 1)
Java Unit 2(Part 1)Java Unit 2(Part 1)
Java Unit 2(Part 1)
SURBHI SAROHA
 

Similar to Using class and object java (20)

C# Language Overview Part II
C# Language Overview Part IIC# Language Overview Part II
C# Language Overview Part II
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptclassandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.ppt
 
5. c sharp language overview part ii
5. c sharp language overview   part ii5. c sharp language overview   part ii
5. c sharp language overview part ii
 
C# overview part 2
C# overview part 2C# overview part 2
C# overview part 2
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
Unit i
Unit iUnit i
Unit i
 
oops-1
oops-1oops-1
oops-1
 
Object oriented programming tutorial
Object oriented programming tutorialObject oriented programming tutorial
Object oriented programming tutorial
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .Net
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
 
Reflection in C#
Reflection in C#Reflection in C#
Reflection in C#
 
07slide.ppt
07slide.ppt07slide.ppt
07slide.ppt
 
Oops
OopsOops
Oops
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programming
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
Lecture 2 classes i
Lecture 2 classes iLecture 2 classes i
Lecture 2 classes i
 
Java Unit 2(Part 1)
Java Unit 2(Part 1)Java Unit 2(Part 1)
Java Unit 2(Part 1)
 

More from mha4

Mule chapter2
Mule chapter2Mule chapter2
Mule chapter2
mha4
 
Mule Introduction
Mule IntroductionMule Introduction
Mule Introduction
mha4
 
Introduce Mule
Introduce MuleIntroduce Mule
Introduce Mule
mha4
 
OOP for java
OOP for javaOOP for java
OOP for java
mha4
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slots
mha4
 
05 junit
05 junit05 junit
05 junit
mha4
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slots
mha4
 

More from mha4 (7)

Mule chapter2
Mule chapter2Mule chapter2
Mule chapter2
 
Mule Introduction
Mule IntroductionMule Introduction
Mule Introduction
 
Introduce Mule
Introduce MuleIntroduce Mule
Introduce Mule
 
OOP for java
OOP for javaOOP for java
OOP for java
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slots
 
05 junit
05 junit05 junit
05 junit
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slots
 

Recently uploaded

DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
Automobile Management System Project Report.pdf
Automobile Management System Project Report.pdfAutomobile Management System Project Report.pdf
Automobile Management System Project Report.pdf
Kamal Acharya
 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
ShahidSultan24
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdfCOLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
Kamal Acharya
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
Kamal Acharya
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
Vaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdfVaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdf
Kamal Acharya
 

Recently uploaded (20)

DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
Automobile Management System Project Report.pdf
Automobile Management System Project Report.pdfAutomobile Management System Project Report.pdf
Automobile Management System Project Report.pdf
 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdfCOLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Vaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdfVaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdf
 

Using class and object java

  • 1. Using Classes and ObjectsUsing Classes and Objects Using the Standard .NET Framework ClassesUsing the Standard .NET Framework Classes Svetlin NakovSvetlin Nakov Telerik CorporationTelerik Corporation www.telerik.comwww.telerik.com
  • 2. Table of ContentsTable of Contents 1.1. Classes and ObjectsClasses and Objects What are Objects?What are Objects? What are Classes?What are Classes? 1.1. Classes in C#Classes in C# Declaring ClassDeclaring Class Fields and Properties: Instance and StaticFields and Properties: Instance and Static Instance and Static MethodsInstance and Static Methods ConstructorsConstructors 1.1. StructuresStructures
  • 3. Table of Contents (2)Table of Contents (2) 4.4. NamespacesNamespaces 5.5. RandomRandom classclass 6.6. Introduction to .NETIntroduction to .NET Common Type SystemCommon Type System
  • 4. Classes and ObjectsClasses and Objects Modeling Real-world Entities with ObjectsModeling Real-world Entities with Objects
  • 5. What are Objects?What are Objects?  Software objects model real-world objects orSoftware objects model real-world objects or abstract conceptsabstract concepts Examples:Examples:  bank, account, customer, dog, bicycle, queuebank, account, customer, dog, bicycle, queue  Real-world objects haveReal-world objects have statesstates andand behaviorsbehaviors Account' states:Account' states:  holder, balance, typeholder, balance, type Account' behaviors:Account' behaviors:  withdraw, deposit, suspendwithdraw, deposit, suspend
  • 6. What are Objects? (2)What are Objects? (2)  How do software objects implement real-How do software objects implement real- world objects?world objects? Use variables/data to implement statesUse variables/data to implement states Use methods/functions to implement behaviorsUse methods/functions to implement behaviors  An object is a software bundle of variables andAn object is a software bundle of variables and related methodsrelated methods
  • 7. Objects RepresentObjects Represent 7 checkschecks peoplepeople shopping listshopping list …… numbersnumbers characterscharacters queuesqueues arraysarrays Things fromThings from the real worldthe real world Things from theThings from the computer worldcomputer world
  • 8. What is Class?What is Class?  The formal definition ofThe formal definition of classclass:: Definition by GoogleDefinition by Google ClassesClasses act as templates from which anact as templates from which an instance of an object is created at runinstance of an object is created at run time. Classes define the properties of thetime. Classes define the properties of the object and the methods used to controlobject and the methods used to control the object's behavior.the object's behavior.
  • 9. 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 ofSet of attributesattributes  Represented by variables and propertiesRepresented by variables and properties  Hold theirHold their statestate Set of actions (Set of actions (behaviorbehavior))  Represented by methodsRepresented by methods  A class defines the methods and types of dataA class defines the methods and types of data associated with an objectassociated with an object
  • 10. Classes – ExampleClasses – Example AccountAccount +Owner: Person+Owner: Person +Ammount: double+Ammount: double +Suspend()+Suspend() +Deposit(sum:double)+Deposit(sum:double) +Withdraw(sum:double)+Withdraw(sum:double) ClassClass NameName AttributesAttributes (Properties(Properties and Fields)and Fields) OperationsOperations (Methods)(Methods)
  • 11. ObjectsObjects  AnAn objectobject is a concreteis a concrete instanceinstance of a particularof a particular classclass  Creating an object from a class is calledCreating an object from a class is called instantiationinstantiation  Objects have stateObjects have state Set of values associated to their attributesSet of values associated to their attributes  Example:Example: Class:Class: AccountAccount Objects: Ivan's account, Peter's accountObjects: Ivan's account, Peter's account
  • 12. Objects – ExampleObjects – Example AccountAccount +Owner: Person+Owner: Person +Ammount: double+Ammount: double +Suspend()+Suspend() +Deposit(sum:double)+Deposit(sum:double) +Withdraw(sum:double)+Withdraw(sum:double) ClassClass ivanAccountivanAccount +Owner="Ivan Kolev"+Owner="Ivan Kolev" +Ammount=5000.0+Ammount=5000.0 peterAccountpeterAccount +Owner="Peter Kirov"+Owner="Peter Kirov" +Ammount=1825.33+Ammount=1825.33 kirilAccountkirilAccount +Owner="Kiril Kirov"+Owner="Kiril Kirov" +Ammount=25.0+Ammount=25.0 ObjectObject ObjectObject ObjectObject
  • 13. Classes in C#Classes in C# Using Classes and their Class MembersUsing Classes and their Class Members
  • 14. Classes in C#Classes in C#  Basic units that compose programsBasic units that compose programs  Implementation isImplementation 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, …)
  • 15. Classes in C# – ExamplesClasses in C# – Examples  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.RandomSystem.Random
  • 16. Declaring ObjectsDeclaring Objects  An instance of a class or structure can beAn instance of a class or structure can be defined like any other variable:defined like any other variable:  Instances cannot be used if they areInstances cannot be used if they are not initializednot initialized using System;using System; ...... // Define two variables of type DateTime// Define two variables of type DateTime DateTime today;DateTime today; DateTime halloween;DateTime halloween; // Declare and initialize a structure instance// Declare and initialize a structure instance DateTime today = DateTime.Now;DateTime today = DateTime.Now;
  • 17. Fields and PropertiesFields and Properties Accessing Fields and PropertiesAccessing Fields and Properties
  • 18. 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 any actions ofAccessing a field doesn’t invoke any actions of the objectthe object  Example:Example: String.EmptyString.Empty (the(the """" string)string)
  • 19. Accessing FieldsAccessing Fields  Constant fields can be only readConstant fields can be only read  Variable fields can be read and modifiedVariable fields can be read and modified  Usually properties are used instead of directlyUsually properties are used instead of directly accessing variable fieldsaccessing variable fields  Examples:Examples: // Accessing read-only field// Accessing read-only field String empty = String.Empty;String empty = String.Empty; // Accessing constant field// Accessing constant field int maxInt = Int32.MaxValue;int maxInt = Int32.MaxValue;
  • 20. PropertiesProperties  Properties look like fields (have name andProperties look like fields (have name and type), but they can contain code, executedtype), but they can contain code, executed when they are accessedwhen they are accessed  Usually used to control access to dataUsually used to control access to data fields (wrappers), but can contain morefields (wrappers), but can contain more complex logiccomplex logic  Can have two components (and at least oneCan have two components (and at least one of them) calledof them) called accessorsaccessors  getget for reading their valuefor reading their value  setset for changing their valuefor changing their value
  • 21. Properties (2)Properties (2)  According to the implemented accessorsAccording to the implemented accessors properties can be:properties can be: Read-only (Read-only (getget accessor only)accessor only) Read and write (bothRead and write (both getget andand 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
  • 22. Accessing PropertiesAccessing Properties and Fields – Exampleand Fields – Example using System;using System; ...... DateTime christmas = new DateTime(2009, 12, 25);DateTime christmas = new DateTime(2009, 12, 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: {2}","Christmas day: {0}, month: {1}, year: {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));
  • 24. Instance and Static MembersInstance and Static Members Accessing Object and Class MembersAccessing Object and Class Members
  • 25. Instance and Static MembersInstance and Static Members  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 objectInstance members are specific for each object Example: different dogs have different nameExample: different dogs have different name  Static members are common for all instancesStatic members are common for all instances of a classof a class Example:Example: DateTime.MinValueDateTime.MinValue is sharedis shared between all instances ofbetween all instances of DateTimeDateTime
  • 26. Accessing Members – SyntaxAccessing Members – Syntax  Accessing instance membersAccessing instance members The name of theThe name of the instanceinstance, followed by the, followed by the name of the member (field or property),name of the member (field or property), separated by dot ("separated by dot ("..")")  Accessing static membersAccessing static members The name of theThe name of the classclass, followed by the name of, followed by the name of the memberthe member <instance_name>.<member_name><instance_name>.<member_name> <class_name>.<member_name><class_name>.<member_name>
  • 27. Instance and StaticInstance and Static Members – ExamplesMembers – Examples  Example of instance memberExample of instance member  String.LengthString.Length  Each string object has different lengthEach string object has different length  Example of static memberExample of static member  Console.ReadLine()Console.ReadLine()  The console is only one (global for the program)The console is only one (global for the program)  Reading from the console does not require toReading from the console does not require to create an instance of itcreate an instance of it
  • 28. MethodsMethods Calling Instance and Static MethodsCalling Instance and Static Methods
  • 29. MethodsMethods  Methods manipulate the data of the object toMethods manipulate the data of the object to which they belong or perform other taskswhich they belong or perform 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)
  • 30. Instance MethodsInstance Methods  Instance methods manipulate the data of aInstance methods manipulate the data of a specified object or perform any other tasksspecified object or perform any other tasks If a value is returned, it depends on theIf a value is returned, it depends on the particular class instanceparticular class instance  Syntax:Syntax: The name of the instance, followed by theThe name of the instance, followed by the name of the method, separated by dotname of the method, separated by dot <object_name>.<method_name>(<parameters>)<object_name>.<method_name>(<parameters>)
  • 31. Calling Instance Methods –Calling Instance Methods – ExamplesExamples  Calling instance methods ofCalling instance methods of StringString::  Calling instance methods ofCalling 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); // aaaaa Console.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}", later);Console.WriteLine("8 hours later: {0}", later);
  • 32. Calling Instance MethodsCalling Instance Methods Live DemoLive Demo
  • 33. Static MethodsStatic Methods  Static methods are common for all instances ofStatic methods are common for all instances of a class (shared between all instances)a class (shared between all instances) Returned value depends only on the passedReturned value depends only on the passed parametersparameters No particular class instance is availableNo particular class instance is available  Syntax:Syntax: The name of the class, followed by the name ofThe name of the class, followed by the name of the method, separated by dotthe method, separated by dot <class_name>.<method_name>(<parameters>)<class_name>.<method_name>(<parameters>)
  • 34. Calling Static Methods – ExamplesCalling Static Methods – Examples 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, round1);"{0}; {1}; {2}", precise, round3, round1); // 8,7654321; 8,765; 8,8// 8,7654321; 8,765; 8,8 ConstantConstant fieldfield StaticStatic methodmethod StaticStatic methometho dd StaticStatic methometho dd
  • 35. Calling Static MethodsCalling Static Methods Live DemoLive Demo
  • 36. ConstructorsConstructors  Constructors are special methods used toConstructors are special methods used to assign initial values of the fields in an objectassign initial values of the fields in an object Executed when an object of a given type isExecuted when an object of a given type is being createdbeing created Have the same name as the class that holdsHave the same name as the class that holds themthem Do not return a valueDo not return a value  A class may have several constructors withA class may have several constructors with different set of parametersdifferent set of parameters
  • 37. Constructors (2)Constructors (2)  Constructor is invoked by theConstructor 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, 59);DateTime dt = new DateTime(2009, 12, 30, 12, 33, 59); Int32 value = new Int32(1024);Int32 value = new Int32(1024);
  • 38. Parameterless ConstructorsParameterless Constructors  The constructor without parameters is calledThe constructor without parameters is called defaultdefault constructorconstructor  Example:Example: Creating an object for generating randomCreating an object for generating random numbers with a default seednumbers with a default seed using System;using System; ...... Random randomGenerator = new Random();Random randomGenerator = new Random(); The classThe class System.RandomSystem.Random providesprovides generation of pseudo-randomgeneration of pseudo-random numbersnumbers ParameterlessParameterless constructorconstructor callcall
  • 39. Constructor With ParametersConstructor With Parameters  ExampleExample Creating objects for generating random valuesCreating objects for generating random values with specified initial seedswith specified initial seeds 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
  • 40. Generating Random NumbersGenerating Random Numbers Live DemoLive Demo
  • 41. More Constructor ExamplesMore Constructor Examples  Creating aCreating a DateTimeDateTime object for a specifiedobject for a specified date and timedate and time  Different constructors are called depending onDifferent constructors are called depending on the different sets of parametersthe different sets of parameters using System;using System; DateTime halloween = new DateTime(2009, 10, 31);DateTime halloween = new DateTime(2009, 10, 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);
  • 43. EnumerationsEnumerations Types Limited to a Predefined Set ofValuesTypes Limited to a Predefined Set ofValues
  • 44. EnumerationsEnumerations  EnumerationsEnumerations in C# are types whose values arein C# are types whose values are limited to a predefined set of valueslimited to a predefined set of values E.g. the days of weekE.g. the days of week Declared by the keywordDeclared 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!
  • 45. StructuresStructures What are Structures? When to Use Them?What are Structures? When to Use Them?
  • 46. StructuresStructures  Structures are similar to classesStructures are similar to classes  Structures are usually used for storing dataStructures are usually used for storing data structures, without any other functionalitystructures, without any other functionality  Structures can have fields, properties, etc.Structures can have fields, properties, etc. Using methods is not recommendedUsing methods is not recommended  Structures areStructures are value typesvalue types, and classes are, and classes are reference typesreference types (this will be discussed later)(this will be discussed later)  Example of structureExample of structure System.DateTimeSystem.DateTime – represents a date and time– represents a date and time
  • 47. NamespacesNamespaces Organizing Classes Logically into NamespacesOrganizing Classes Logically into Namespaces
  • 48. What is a Namespace?What is a Namespace?  Namespaces are used to organize the sourceNamespaces are used to organize the source code into more logical and manageable waycode into more logical and manageable way  Namespaces can containNamespaces can contain Definitions of classes, structures, interfaces andDefinitions of classes, structures, interfaces and other types and other namespacesother types and other namespaces  Namespaces can contain other namespacesNamespaces can contain other namespaces  For example:For example: SystemSystem namespace containsnamespace contains DataData namespacenamespace The name of the nested namespace isThe name of the nested namespace is System.DataSystem.Data
  • 49. Full Class NamesFull Class Names  A full name of a class is the name of the classA full name of a class is the name of the class preceded by the name of its namespacepreceded by the name of its namespace  Example:Example: ArrayArray class, defined in theclass, defined in the SystemSystem namespacenamespace The full name of the class isThe full name of the class is System.ArraySystem.Array <namespace_name>.<class_name><namespace_name>.<class_name>
  • 50. Including NamespacesIncluding Namespaces  TheThe usingusing directive in C#:directive in C#:  Allows using types in a namespace, withoutAllows using types in a namespace, without specifying their full namespecifying 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;
  • 51. Random ClassRandom Class Password Generator DemoPassword Generator Demo 51
  • 52. TheThe RandomRandom ClassClass  TheThe RandomRandom classclass Generates random integer numbersGenerates random integer numbers  bytebyte oror 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 numbers from 1 toThis generates six random numbers from 1 to 4949  TheThe Next()Next() method returns a randommethod returns a random numbernumber
  • 53. Password GeneratorPassword Generator  Generates a random password between 8 and 15Generates a random password between 8 and 15 characterscharacters  The password contains of at least two capitalThe password contains of at least two capital letters, two small letters, one digit and threeletters, two small letters, one digit and three special charactersspecial characters  Constructing the Password Generator class:Constructing the Password Generator class:  Start from empty passwordStart from empty password  Place two random capital letters at randomPlace two random capital letters at random positionspositions  Place two random small letters at random positionsPlace two random small letters at random positions  Place one random digit at random positionsPlace one random digit at random positions  Place three special characters at random positionsPlace three special characters at random positions 53
  • 54. 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 weTo make the length between 8 and 15 we generate a number N between 0 and 7generate a number N between 0 and 7 And then inserts N random characters ( capitalAnd then inserts N random characters ( capital letter or small letter or digit or specialletter or small letter or digit or special character) at random positionscharacter) at random positions 54
  • 55. class RandomPasswordGeneratorclass RandomPasswordGenerator {{ private const stringprivate const string CapitalLettersCapitalLetters== "ABCDEFGHIJKLMNOPQRSTUVWXYZ";"ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private const stringprivate const string SmallLettersSmallLetters == "abcdefghijklmnopqrstuvwxyz";"abcdefghijklmnopqrstuvwxyz"; private const stringprivate const string DigitsDigits = "0123456789";= "0123456789"; pprivate const stringrivate const string SpecialCharsSpecialChars == "~!@#$%^&*()_+=`{}[]|':;.,/?<>";"~!@#$%^&*()_+=`{}[]|':;.,/?<>"; private const stringprivate const string AllCharsAllChars == CapitalLettersCapitalLetters ++ SmallLettersSmallLetters ++ DigitsDigits ++ SpecialCharsSpecialChars;; private static Random rnd = new Random();private static Random rnd = new Random(); // the example continues…// the example continues… Password Generator ClassPassword Generator Class
  • 56. Password Generator ClassPassword Generator Class 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…
  • 57. Password Generator ClassPassword Generator Class 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; }}
  • 58. .NET CommonType System.NET CommonType System Brief IntroductionBrief Introduction
  • 59. Common Type System (CTS)Common Type System (CTS)  CTS defines all dataCTS defines all data typestypes supported in .NETsupported in .NET FrameworkFramework 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
  • 60. CTS and Different LanguagesCTS and Different Languages  CTS is common for all .NET languagesCTS is common for all .NET languages 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
  • 61. Value and Reference TypesValue and Reference Types  In CTS there are two categories of typesIn CTS there are two categories of types ValueValue typestypes Reference typesReference types  Placed in different areas of memoryPlaced in different areas of memory Value types live in theValue types live in the execution stackexecution stack  Freed when become out of scopeFreed when become out of scope Reference types live in theReference types live in the managed heapmanaged heap (dynamic memory)(dynamic memory)  Freed by theFreed by the garbage collectorgarbage collector
  • 62. Value and Reference Types –Value and Reference Types – ExamplesExamples  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[]
  • 63. System.Object: CTS Base TypeSystem.Object: CTS Base Type  System.ObjectSystem.Object ((objectobject in C#) is a basein C#) is a base typetype for all other typesfor all other types in CTSin CTS Can hold values of any other type:Can hold values of any other type:  All .NET types derive common methods fromAll .NET types derive common 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);
  • 64. SummarySummary  Classes provide the structure for objectsClasses provide the structure for objects  Objects are particular instances of classesObjects are particular instances of classes  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
  • 65. Summary (2)Summary (2)  Namespaces help organizing the classesNamespaces help organizing the classes  Common Type System (CTS) defines the typesCommon Type System (CTS) defines the types for all .NET languagesfor all .NET languages Values typesValues types Reference typesReference types
  • 66. Questions?Questions? Using Classes and ObjectsUsing Classes and Objects http://academy.telerik.com
  • 67. ExercisesExercises 1.1. Write a program that reads a year from the consoleWrite a program that reads a year from the console and checks whether it is a leap. Useand checks whether it is a leap. Use DateTimeDateTime.. 2.2. Write a program that generates and prints to theWrite a program that generates and prints to the console 10 random values in the range [100, 200].console 10 random values in the range [100, 200]. 3.3. Write a program that prints to the console which dayWrite a program that prints to the console which day of the week is today. Useof the week is today. Use System.DateTimeSystem.DateTime.. 4.4. Write methods that calculate the surface of a triangleWrite methods that calculate the surface of a triangle by given:by given:  Side and an altitude to it; Three sides; Two sidesSide and an altitude to it; Three sides; Two sides and an angle between them. Useand an angle between them. Use System.MathSystem.Math..
  • 68. Exercises (2)Exercises (2) 5.5. Write a method that calculates the number ofWrite a method that calculates the number of workdays between today and given date, passed asworkdays between today and given date, passed as parameter. Consider that workdays are all days fromparameter. Consider that workdays are all days from Monday to Friday except a fixed array of publicMonday to 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 valuesYou are given a sequence of positive integer values written into a string, separated by spaces. Write awritten into a string, separated by spaces. Write a function that reads these values from given stringfunction that reads these values from given string and calculates their sum. Example:and calculates their sum. Example: string = "string = "43 68 9 23 31843 68 9 23 318""  result =result = 461461
  • 69. Exercises (3)Exercises (3) 7.7. * Write a program that calculates the value of given* Write a program that calculates the value of given arithmetical expression. The expression can containarithmetical expression. The expression can contain the following elements only: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 priorities)(standard 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 classicalHint: Use the classical "shunting yard" algorithm"shunting yard" algorithm andand "reverse Polish notation""reverse Polish notation"..