Classes provide templates for objects by defining attributes and behaviors. An object is an instance of a class that holds specific state through its attribute values. Classes in C# can contain fields to store data, properties for encapsulated access to fields, methods to implement behaviors, and constructors to initialize objects. Constructors are special methods that are called when an object is instantiated and assign initial field values.
This slide is based on Object Oriented Programming Language. Here is some details about object and class. You can easily understand about object and class.
This slide is based on Object Oriented Programming Language. Here is some details about object and class. You can easily understand about object and class.
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
The lecture was condcuted by Tushar B Kute at YCMOU, Nashik through VLC orgnanized by MSBTE. The contents can be found in book "Core Java Programming - A Practical Approach' by Laxmi Publications.
Pdf Covers-- Concept of OOPS, Introduction to Java, Java Features, History of Java, Naming of Java, Java version release, Structure of Java Program, Creating a Simple Java Program, Java Virtual Machine
OOPS Concepts, Java Evolution, Class Object basic, Class Object Constructor overloading, Inheritance, Array and String, Final Abstract class and interfaces, Exceptions, Streams, GUI Applications, Applet Programming, Network Programming and Java Sockets, Multi Threading
Method overloading, recursion, passing and returning objects from method, new...JAINAM KAPADIYA
Method and Method overloading
How to overload method in JAVA?
Method overloading Examples of the program.
New operator
Recursion
Passing and returning objects from methods.
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
The lecture was condcuted by Tushar B Kute at YCMOU, Nashik through VLC orgnanized by MSBTE. The contents can be found in book "Core Java Programming - A Practical Approach' by Laxmi Publications.
Pdf Covers-- Concept of OOPS, Introduction to Java, Java Features, History of Java, Naming of Java, Java version release, Structure of Java Program, Creating a Simple Java Program, Java Virtual Machine
OOPS Concepts, Java Evolution, Class Object basic, Class Object Constructor overloading, Inheritance, Array and String, Final Abstract class and interfaces, Exceptions, Streams, GUI Applications, Applet Programming, Network Programming and Java Sockets, Multi Threading
Method overloading, recursion, passing and returning objects from method, new...JAINAM KAPADIYA
Method and Method overloading
How to overload method in JAVA?
Method overloading Examples of the program.
New operator
Recursion
Passing and returning objects from methods.
Object oriented programming by timehubzone.com.
To understand the object-oriented features and how best to use them, it is helpful to understand the key concepts of object-oriented programming. This section is a brief introduction to object-oriented programming. It also compares these concepts with features of procedural programming used to accomplish the same goals
https://www.timehubzone.com/worldclock
The timehubzone.com is a web service that transforms, otherwise tricky, tasks like your assistant as you go and makes travel easy on tour, travel, international meeting into an intuitive, super-quick and painless experience.
https://www.timehubzone.com/holidays
This is a presentation I did for the Cedar Rapids .NET User Group (CRineta.org). It was intended to present object oriented concepts and their application in .NET and C#.
Saudi Arabia stands as a titan in the global energy landscape, renowned for its abundant oil and gas resources. It's the largest exporter of petroleum and holds some of the world's most significant reserves. Let's delve into the top 10 oil and gas projects shaping Saudi Arabia's energy future in 2024.
About
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
• Remote control: Parallel or serial interface.
• Compatible with MAFI CCR system.
• Compatible with IDM8000 CCR.
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
• Easy in configuration using DIP switches.
Technical Specifications
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
Key Features
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
• Remote control: Parallel or serial interface
• Compatible with MAFI CCR system
• Copatiable with IDM8000 CCR
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
Application
• Remote control: Parallel or serial interface.
• Compatible with MAFI CCR system.
• Compatible with IDM8000 CCR.
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
• Easy in configuration using DIP switches.
Immunizing Image Classifiers Against Localized Adversary Attacksgerogepatton
This paper addresses the vulnerability of deep learning models, particularly convolutional neural networks
(CNN)s, to adversarial attacks and presents a proactive training technique designed to counter them. We
introduce a novel volumization algorithm, which transforms 2D images into 3D volumetric representations.
When combined with 3D convolution and deep curriculum learning optimization (CLO), itsignificantly improves
the immunity of models against localized universal attacks by up to 40%. We evaluate our proposed approach
using contemporary CNN architectures and the modified Canadian Institute for Advanced Research (CIFAR-10
and CIFAR-100) and ImageNet Large Scale Visual Recognition Challenge (ILSVRC12) datasets, showcasing
accuracy improvements over previous techniques. The results indicate that the combination of the volumetric
input and curriculum learning holds significant promise for mitigating adversarial attacks without necessitating
adversary training.
Automobile Management System Project Report.pdfKamal Acharya
The proposed project is developed to manage the automobile in the automobile dealer company. The main module in this project is login, automobile management, customer management, sales, complaints and reports. The first module is the login. The automobile showroom owner should login to the project for usage. The username and password are verified and if it is correct, next form opens. If the username and password are not correct, it shows the error message.
When a customer search for a automobile, if the automobile is available, they will be taken to a page that shows the details of the automobile including automobile name, automobile ID, quantity, price etc. “Automobile Management System” is useful for maintaining automobiles, customers effectively and hence helps for establishing good relation between customer and automobile organization. It contains various customized modules for effectively maintaining automobiles and stock information accurately and safely.
When the automobile is sold to the customer, stock will be reduced automatically. When a new purchase is made, stock will be increased automatically. While selecting automobiles for sale, the proposed software will automatically check for total number of available stock of that particular item, if the total stock of that particular item is less than 5, software will notify the user to purchase the particular item.
Also when the user tries to sale items which are not in stock, the system will prompt the user that the stock is not enough. Customers of this system can search for a automobile; can purchase a automobile easily by selecting fast. On the other hand the stock of automobiles can be maintained perfectly by the automobile shop manager overcoming the drawbacks of existing system.
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdffxintegritypublishin
Advancements in technology unveil a myriad of electrical and electronic breakthroughs geared towards efficiently harnessing limited resources to meet human energy demands. The optimization of hybrid solar PV panels and pumped hydro energy supply systems plays a pivotal role in utilizing natural resources effectively. This initiative not only benefits humanity but also fosters environmental sustainability. The study investigated the design optimization of these hybrid systems, focusing on understanding solar radiation patterns, identifying geographical influences on solar radiation, formulating a mathematical model for system optimization, and determining the optimal configuration of PV panels and pumped hydro storage. Through a comparative analysis approach and eight weeks of data collection, the study addressed key research questions related to solar radiation patterns and optimal system design. The findings highlighted regions with heightened solar radiation levels, showcasing substantial potential for power generation and emphasizing the system's efficiency. Optimizing system design significantly boosted power generation, promoted renewable energy utilization, and enhanced energy storage capacity. The study underscored the benefits of optimizing hybrid solar PV panels and pumped hydro energy supply systems for sustainable energy usage. Optimizing the design of solar PV panels and pumped hydro energy supply systems as examined across diverse climatic conditions in a developing country, not only enhances power generation but also improves the integration of renewable energy sources and boosts energy storage capacities, particularly beneficial for less economically prosperous regions. Additionally, the study provides valuable insights for advancing energy research in economically viable areas. Recommendations included conducting site-specific assessments, utilizing advanced modeling tools, implementing regular maintenance protocols, and enhancing communication among system components.
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdfKamal Acharya
The College Bus Management system is completely developed by Visual Basic .NET Version. The application is connect with most secured database language MS SQL Server. The application is develop by using best combination of front-end and back-end languages. The application is totally design like flat user interface. This flat user interface is more attractive user interface in 2017. The application is gives more important to the system functionality. The application is to manage the student’s details, driver’s details, bus details, bus route details, bus fees details and more. The application has only one unit for admin. The admin can manage the entire application. The admin can login into the application by using username and password of the admin. The application is develop for big and small colleges. It is more user friendly for non-computer person. Even they can easily learn how to manage the application within hours. The application is more secure by the admin. The system will give an effective output for the VB.Net and SQL Server given as input to the system. The compiled java program given as input to the system, after scanning the program will generate different reports. The application generates the report for users. The admin can view and download the report of the data. The application deliver the excel format reports. Because, excel formatted reports is very easy to understand the income and expense of the college bus. This application is mainly develop for windows operating system users. In 2017, 73% of people enterprises are using windows operating system. So the application will easily install for all the windows operating system users. The application-developed size is very low. The application consumes very low space in disk. Therefore, the user can allocate very minimum local disk space for this application.
Courier management system project report.pdfKamal Acharya
It is now-a-days very important for the people to send or receive articles like imported furniture, electronic items, gifts, business goods and the like. People depend vastly on different transport systems which mostly use the manual way of receiving and delivering the articles. There is no way to track the articles till they are received and there is no way to let the customer know what happened in transit, once he booked some articles. In such a situation, we need a system which completely computerizes the cargo activities including time to time tracking of the articles sent. This need is fulfilled by Courier Management System software which is online software for the cargo management people that enables them to receive the goods from a source and send them to a required destination and track their status from time to time.
Welcome to WIPAC Monthly the magazine brought to you by the LinkedIn Group Water Industry Process Automation & Control.
In this month's edition, along with this month's industry news to celebrate the 13 years since the group was created we have articles including
A case study of the used of Advanced Process Control at the Wastewater Treatment works at Lleida in Spain
A look back on an article on smart wastewater networks in order to see how the industry has measured up in the interim around the adoption of Digital Transformation in the Water Industry.
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxR&R Consult
CFD analysis is incredibly effective at solving mysteries and improving the performance of complex systems!
Here's a great example: At a large natural gas-fired power plant, where they use waste heat to generate steam and energy, they were puzzled that their boiler wasn't producing as much steam as expected.
R&R and Tetra Engineering Group Inc. were asked to solve the issue with reduced steam production.
An inspection had shown that a significant amount of hot flue gas was bypassing the boiler tubes, where the heat was supposed to be transferred.
R&R Consult conducted a CFD analysis, which revealed that 6.3% of the flue gas was bypassing the boiler tubes without transferring heat. The analysis also showed that the flue gas was instead being directed along the sides of the boiler and between the modules that were supposed to capture the heat. This was the cause of the reduced performance.
Based on our results, Tetra Engineering installed covering plates to reduce the bypass flow. This improved the boiler's performance and increased electricity production.
It is always satisfying when we can help solve complex challenges like this. Do your systems also need a check-up or optimization? Give us a call!
Work done in cooperation with James Malloy and David Moelling from Tetra Engineering.
More examples of our work https://www.r-r-consult.dk/en/cases-en/
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Dr.Costas Sachpazis
Terzaghi's soil bearing capacity theory, developed by Karl Terzaghi, is a fundamental principle in geotechnical engineering used to determine the bearing capacity of shallow foundations. This theory provides a method to calculate the ultimate bearing capacity of soil, which is the maximum load per unit area that the soil can support without undergoing shear failure. The Calculation HTML Code included.
Water scarcity is the lack of fresh water resources to meet the standard water demand. There are two type of water scarcity. One is physical. The other is economic water scarcity.
Overview of the fundamental roles in Hydropower generation and the components involved in wider Electrical Engineering.
This paper presents the design and construction of hydroelectric dams from the hydrologist’s survey of the valley before construction, all aspects and involved disciplines, fluid dynamics, structural engineering, generation and mains frequency regulation to the very transmission of power through the network in the United Kingdom.
Author: Robbie Edward Sayers
Collaborators and co editors: Charlie Sims and Connor Healey.
(C) 2024 Robbie E. Sayers
Vaccine management system project report documentation..pdfKamal Acharya
The Division of Vaccine and Immunization is facing increasing difficulty monitoring vaccines and other commodities distribution once they have been distributed from the national stores. With the introduction of new vaccines, more challenges have been anticipated with this additions posing serious threat to the already over strained vaccine supply chain system in Kenya.
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
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
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;
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
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>)
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>)
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
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);
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!
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
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;
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…
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
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"..