9. Building .NET-based Applications with C#
1. Examining Microsoft .NET Framework class library
2. The Object Browser
3. Overriding Methods from System.Object class
4. Formatting Strings, Numbers, Currency and date values.
5. Using Streams and Files: Read and Write both Binary and Text Files, Using FileStream
6. Serialization and De-serialization.
This document summarizes a lecture about models of evaluation in Haskell. It discusses lazy evaluation and call-by-need evaluation in Haskell. It provides examples showing that expressions are not evaluated unless their values are needed. Common functions like map and fold can be written in terms of each other due to their shared structural transformation of lists. Both left and right folds are discussed, with right folds constructing nested applications and left folds avoiding this issue.
This document discusses various topics related to Haskell and functional programming:
1. It defines functions for adding, subtracting, and multiplying quaternions. However, quaternion multiplication is not commutative, so it cannot fully implement the Num typeclass.
2. It introduces the Maybe type for handling potential failure cases in functions like division or accessing the head of an empty list.
3. It defines a Tree type for representing binary trees and functions like mapping and calculating size.
4. It generalizes the idea of mapping with the Functor typeclass, showing instances for lists, Maybe, and trees. Homework involves making the Tree type into a binary search tree and adapting it for a key-value container
This document summarizes Lecture 1 of Real World Haskell. It introduces functional programming and Haskell, discusses the Haskell Platform and interactive interpreter ghci. It demonstrates defining simple functions and expressions, writing small interactive programs, and using recursion to number lines of text. Resources for learning more about Haskell are provided.
The document discusses types in Haskell, explaining that Haskell is strongly typed and describing basic types like Int, Char, and Bool as well as more complex types like tuples, lists, and functions. It also covers type inference, polymorphism, and how to infer the behavior of functions from their types.
The document discusses Haskell concepts including:
1) Pattern matching allows functions to handle different cases depending on the structure of input data, like matching empty and non-empty lists.
2) Guards allow selecting different code blocks based on Boolean conditions.
3) Combining pattern matching and guards allows for very expressive functions that concisely handle multiple cases.
4) Metasyntactic variables like (x:xs) follow conventions to bind pattern names and make code more readable.
5) Functions can match multiple patterns at once to handle different input structures.
This document discusses object initialization in Java. It explains that in Java, constructors allow objects to be initialized when they are created. Constructors ensure that class member variables and objects are properly initialized before use. The document provides examples of how to write classes with constructors and use constructor overloading. It also discusses static initialization, the this keyword, and recursion.
The Functional Programming Triad of Map, Filter and FoldPhilip Schwarz
This slide deck is my homage to SICP, the book which first introduced me to the Functional Programming triad of map, filter and fold.
It was during my Computer Science degree that a fellow student gave me a copy of the first edition, not long after the book came out.
I have not yet come across a better introduction to these three functions.
The upcoming slides are closely based on the second edition of the book, a free online copy of which can be found here:
https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book.html.
Download for original image quality.
Errata:
slide 20: the Clojure map function is in fact the Scheme one repeated - see code below for correction.
Scheme code: https://github.com/philipschwarz/the-fp-triad-of-map-filter-and-fold-scheme
Clojure code: https://github.com/philipschwarz/the-fp-triad-of-map-filter-and-fold-clojure
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...Philip Schwarz
See how feeding FP workhorses map and filter with monadic steroids turns them into the intriguing mapM and filterM.
Graduate to foldM by learning how it behaves with the help of three simple yet instructive examples of its usage.
Use the powers of foldM to generate all permutations of a collection with a simple one-liner.
Exploit what you learned about foldM to solve the N-Queens Combinatorial Problem with an iterative approach rather than a recursive one.
This document summarizes a lecture about models of evaluation in Haskell. It discusses lazy evaluation and call-by-need evaluation in Haskell. It provides examples showing that expressions are not evaluated unless their values are needed. Common functions like map and fold can be written in terms of each other due to their shared structural transformation of lists. Both left and right folds are discussed, with right folds constructing nested applications and left folds avoiding this issue.
This document discusses various topics related to Haskell and functional programming:
1. It defines functions for adding, subtracting, and multiplying quaternions. However, quaternion multiplication is not commutative, so it cannot fully implement the Num typeclass.
2. It introduces the Maybe type for handling potential failure cases in functions like division or accessing the head of an empty list.
3. It defines a Tree type for representing binary trees and functions like mapping and calculating size.
4. It generalizes the idea of mapping with the Functor typeclass, showing instances for lists, Maybe, and trees. Homework involves making the Tree type into a binary search tree and adapting it for a key-value container
This document summarizes Lecture 1 of Real World Haskell. It introduces functional programming and Haskell, discusses the Haskell Platform and interactive interpreter ghci. It demonstrates defining simple functions and expressions, writing small interactive programs, and using recursion to number lines of text. Resources for learning more about Haskell are provided.
The document discusses types in Haskell, explaining that Haskell is strongly typed and describing basic types like Int, Char, and Bool as well as more complex types like tuples, lists, and functions. It also covers type inference, polymorphism, and how to infer the behavior of functions from their types.
The document discusses Haskell concepts including:
1) Pattern matching allows functions to handle different cases depending on the structure of input data, like matching empty and non-empty lists.
2) Guards allow selecting different code blocks based on Boolean conditions.
3) Combining pattern matching and guards allows for very expressive functions that concisely handle multiple cases.
4) Metasyntactic variables like (x:xs) follow conventions to bind pattern names and make code more readable.
5) Functions can match multiple patterns at once to handle different input structures.
This document discusses object initialization in Java. It explains that in Java, constructors allow objects to be initialized when they are created. Constructors ensure that class member variables and objects are properly initialized before use. The document provides examples of how to write classes with constructors and use constructor overloading. It also discusses static initialization, the this keyword, and recursion.
The Functional Programming Triad of Map, Filter and FoldPhilip Schwarz
This slide deck is my homage to SICP, the book which first introduced me to the Functional Programming triad of map, filter and fold.
It was during my Computer Science degree that a fellow student gave me a copy of the first edition, not long after the book came out.
I have not yet come across a better introduction to these three functions.
The upcoming slides are closely based on the second edition of the book, a free online copy of which can be found here:
https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book.html.
Download for original image quality.
Errata:
slide 20: the Clojure map function is in fact the Scheme one repeated - see code below for correction.
Scheme code: https://github.com/philipschwarz/the-fp-triad-of-map-filter-and-fold-scheme
Clojure code: https://github.com/philipschwarz/the-fp-triad-of-map-filter-and-fold-clojure
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...Philip Schwarz
See how feeding FP workhorses map and filter with monadic steroids turns them into the intriguing mapM and filterM.
Graduate to foldM by learning how it behaves with the help of three simple yet instructive examples of its usage.
Use the powers of foldM to generate all permutations of a collection with a simple one-liner.
Exploit what you learned about foldM to solve the N-Queens Combinatorial Problem with an iterative approach rather than a recursive one.
This document provides a 3-sentence summary of the given document:
The document is a tutorial introduction to high-performance Haskell that covers topics like lazy evaluation, reasoning about space usage, benchmarking, profiling, and making Haskell code run faster. It explains concepts like laziness, thunks, and strictness and shows how to define tail-recursive functions, use foldl' for a strict left fold, and force evaluation of data constructor arguments to avoid space leaks. The goal is to help programmers optimize Haskell code and make efficient use of multiple processor cores.
Presented online for C++ on Sea (2020-07-17)
Video at https://www.youtube.com/watch?v=Bai1DTcCHVE
Lambdas. All the cool kid languages have them. But does lambda mean what C++ and other languages, from Java to Python, mean by lambda? Where did lambdas come from? What were they originally for? What is their relationship to data abstraction?
In this session we will into the history, the syntax, the uses and abuses of lambdas and the way in which lambda constructs in C++ and other languages do (or do not) match the original construct introduced in lambda calculus.
The document discusses functions and objects in JavaScript. It defines a function as a reusable block of code that performs operations to fulfill a specific task. Functions can be invoked to execute their code. Objects are collections of properties and methods that represent real-world entities. The document describes how to create user-defined functions and objects in JavaScript, including defining properties and methods. It also provides examples of the built-in String and Math objects and their properties and methods.
The document discusses strings and StringBuffers in Java. Strings are immutable sequences of characters represented by the String class. StringBuffers allow modifying character sequences and are represented by the StringBuffer class. The summary provides an overview of common string and StringBuffer operations like concatenation, extraction, comparison, and modification.
‘go-to’ general-purpose sequential collections -from Java To ScalaPhilip Schwarz
The simple idea of this slide deck is that it collects in a single place quite a bit of information that can be used to gain a basic understanding of some key differences between the ’goto’ sequential collections of Java and Scala.
Errata:
* the twitter handle of Daniel Westheide is @kaffeecoder and not @cafeecoder
* on slide 35, the numbers 215, 220, 225 and 230, should be 2^15, 2^20, 2^25 and 2^30 respectively
* on slide 54, the bottom left node should be green rather than black
The document discusses Google's Guava library and provides examples of how to use some of its main utilities and features. It summarizes Guava's basic utilities like Objects, Preconditions, Joiner and Splitter. It also covers Guava's collections, functions/predicates and MapMaker features and provides code examples for each.
The document discusses the StringBuffer class in Java. Some key points:
- StringBuffer is like String but mutable and growable, used for string concatenation.
- It has methods to append, insert, delete, and modify characters. As characters are added and removed, the StringBuffer will automatically increase capacity if needed.
- Common methods include append(), insert(), delete(), replace(), reverse(), and substring() to modify the character sequence within a StringBuffer.
Slideshare hasn't imported my notes, so here's the link to the Google Presentation: https://goo.gl/Gl4Vhm
Haskell is a statically typed, non strict, pure functional programming language. It is often talked and blogged about, but rarely used commercially. This talk starts with a brief overview of the language, then explains how Haskell is evaluated and how it deals with non-determinism and side effects using only pure functions. The suitability of Haskell for real world data science is then discussed, along with some examples of its users, a small Haskell-powered visualization, and an overview of useful packages for data science. Finally, Accelerate is introduced, an embedded DSL for array computations on the GPU, and an ongoing attempt to use it as the basis for a deep learning package.
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...Philip Schwarz
See how the guard function has migrated from MonadPlus to Alternative and learn something about the latter.
Learn how to write a Scala program that draws an N-Queens solution board using the Doodle graphics library.
See how to write the equivalent Haskell program using the Gloss graphics library.
Learn how to use Monoid and Foldable to compose images both in Haskell and in Scala.
Link to part 1: https://www.slideshare.net/pjschwarz/nqueens-combinatorial-problem-polyglot-fp-for-fun-and-profit-haskell-and-scala-part-1
Errata:
On slide 22, the last line of the showQueens function should of course be show(solution).draw(frame) rather than show(solution).draw
On slide 43, it would be better if the definitions of the beside, above and on Monoids were also shown.
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Philip Schwarz
(download for flawless image quality) Can a left fold ever work over an infinite list? What about a right fold? Find out.
Learn about the other two functions used by functional programmers to implement mathematical induction: iterating and scanning.
Learn about the limitations of the accumulator technique and about tupling, a technique that is the dual of the accumulator trick.
Functional Programming by Examples using Haskellgoncharenko
The document discusses functional programming concepts in Haskell compared to traditional imperative languages like C++. It provides:
1) An example of quicksort implemented in both C++ and Haskell to illustrate the differences in approach and syntax between the two paradigms. The Haskell version is much more concise, using only 5 lines compared to 14 lines in C++.
2) Explanations of key functional programming concepts in Haskell including pure functions, recursion, pattern matching, and higher-order functions like map and fold.
3) Examples and definitions of commonly used Haskell functions and data types to summarize lists, sorting, and traversing elements - highlighting the more declarative style of functional programming.
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Philip Schwarz
(download for best quality slides) Gain a deeper understanding of why right folds over very large and infinite lists are sometimes possible in Haskell.
See how lazy evaluation and function strictness affect left and right folds in Haskell.
Learn when an ordinary left fold results in a space leak and how to avoid it using a strict left fold.
This version eliminates some minor imperfections and corrects the following two errors:
slide 15: "as sharing is required" should be "as sharing is not required"
slide 43: 푠푓표푙푑푙 (⊕) 푎 should be 푠푓표푙푑푙 (⊕) 푒
An array is a container that holds a fixed number of elements of the same type. An array's length is established at creation and cannot be changed. Each element has an index number starting from 0. The document demonstrates how to declare, initialize, access, and copy array elements in Java. It also discusses multidimensional arrays.
String objects are immutable in Java, so any operation that modifies a String value actually creates a new String object. The StringBuffer and StringBuilder classes provide mutable alternatives to String that have similar methods but do not create new objects with each modification. When a String literal value is used in code, it is stored in the String constant pool to promote reuse of these immutable objects.
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5Philip Schwarz
(download for best quality slides) Gain a deeper understanding of why right folds over very large and infinite lists are sometimes possible in Haskell.
See how lazy evaluation and function strictness affect left and right folds in Haskell.
Learn when an ordinary left fold results in a space leak and how to avoid it using a strict left fold.
Errata:
slide 15: "as sharing is required" should be "as sharing is not required"
slide 43: 𝑠𝑓𝑜𝑙𝑑𝑙 (⊕) 𝑎 should be 𝑠𝑓𝑜𝑙𝑑𝑙 (⊕) 𝑒
Stuck with your Ruby Programming Assignment. Get 24/7 help from tutors with Phd in the subject. Email us at support@helpwithassignment.com
Reach us at http://www.HelpWithAssignment.com
This document provides information about C++ classes and objects. It discusses arrays of class objects, static members and variables, const member functions, and string objects. It also includes examples of catching bugs in C++ code snippets and implementing classes for points, polygons, and rectangles.
This document provides a 3-sentence summary of the given document:
The document is a tutorial introduction to high-performance Haskell that covers topics like lazy evaluation, reasoning about space usage, benchmarking, profiling, and making Haskell code run faster. It explains concepts like laziness, thunks, and strictness and shows how to define tail-recursive functions, use foldl' for a strict left fold, and force evaluation of data constructor arguments to avoid space leaks. The goal is to help programmers optimize Haskell code and make efficient use of multiple processor cores.
Presented online for C++ on Sea (2020-07-17)
Video at https://www.youtube.com/watch?v=Bai1DTcCHVE
Lambdas. All the cool kid languages have them. But does lambda mean what C++ and other languages, from Java to Python, mean by lambda? Where did lambdas come from? What were they originally for? What is their relationship to data abstraction?
In this session we will into the history, the syntax, the uses and abuses of lambdas and the way in which lambda constructs in C++ and other languages do (or do not) match the original construct introduced in lambda calculus.
The document discusses functions and objects in JavaScript. It defines a function as a reusable block of code that performs operations to fulfill a specific task. Functions can be invoked to execute their code. Objects are collections of properties and methods that represent real-world entities. The document describes how to create user-defined functions and objects in JavaScript, including defining properties and methods. It also provides examples of the built-in String and Math objects and their properties and methods.
The document discusses strings and StringBuffers in Java. Strings are immutable sequences of characters represented by the String class. StringBuffers allow modifying character sequences and are represented by the StringBuffer class. The summary provides an overview of common string and StringBuffer operations like concatenation, extraction, comparison, and modification.
‘go-to’ general-purpose sequential collections -from Java To ScalaPhilip Schwarz
The simple idea of this slide deck is that it collects in a single place quite a bit of information that can be used to gain a basic understanding of some key differences between the ’goto’ sequential collections of Java and Scala.
Errata:
* the twitter handle of Daniel Westheide is @kaffeecoder and not @cafeecoder
* on slide 35, the numbers 215, 220, 225 and 230, should be 2^15, 2^20, 2^25 and 2^30 respectively
* on slide 54, the bottom left node should be green rather than black
The document discusses Google's Guava library and provides examples of how to use some of its main utilities and features. It summarizes Guava's basic utilities like Objects, Preconditions, Joiner and Splitter. It also covers Guava's collections, functions/predicates and MapMaker features and provides code examples for each.
The document discusses the StringBuffer class in Java. Some key points:
- StringBuffer is like String but mutable and growable, used for string concatenation.
- It has methods to append, insert, delete, and modify characters. As characters are added and removed, the StringBuffer will automatically increase capacity if needed.
- Common methods include append(), insert(), delete(), replace(), reverse(), and substring() to modify the character sequence within a StringBuffer.
Slideshare hasn't imported my notes, so here's the link to the Google Presentation: https://goo.gl/Gl4Vhm
Haskell is a statically typed, non strict, pure functional programming language. It is often talked and blogged about, but rarely used commercially. This talk starts with a brief overview of the language, then explains how Haskell is evaluated and how it deals with non-determinism and side effects using only pure functions. The suitability of Haskell for real world data science is then discussed, along with some examples of its users, a small Haskell-powered visualization, and an overview of useful packages for data science. Finally, Accelerate is introduced, an embedded DSL for array computations on the GPU, and an ongoing attempt to use it as the basis for a deep learning package.
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...Philip Schwarz
See how the guard function has migrated from MonadPlus to Alternative and learn something about the latter.
Learn how to write a Scala program that draws an N-Queens solution board using the Doodle graphics library.
See how to write the equivalent Haskell program using the Gloss graphics library.
Learn how to use Monoid and Foldable to compose images both in Haskell and in Scala.
Link to part 1: https://www.slideshare.net/pjschwarz/nqueens-combinatorial-problem-polyglot-fp-for-fun-and-profit-haskell-and-scala-part-1
Errata:
On slide 22, the last line of the showQueens function should of course be show(solution).draw(frame) rather than show(solution).draw
On slide 43, it would be better if the definitions of the beside, above and on Monoids were also shown.
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Philip Schwarz
(download for flawless image quality) Can a left fold ever work over an infinite list? What about a right fold? Find out.
Learn about the other two functions used by functional programmers to implement mathematical induction: iterating and scanning.
Learn about the limitations of the accumulator technique and about tupling, a technique that is the dual of the accumulator trick.
Functional Programming by Examples using Haskellgoncharenko
The document discusses functional programming concepts in Haskell compared to traditional imperative languages like C++. It provides:
1) An example of quicksort implemented in both C++ and Haskell to illustrate the differences in approach and syntax between the two paradigms. The Haskell version is much more concise, using only 5 lines compared to 14 lines in C++.
2) Explanations of key functional programming concepts in Haskell including pure functions, recursion, pattern matching, and higher-order functions like map and fold.
3) Examples and definitions of commonly used Haskell functions and data types to summarize lists, sorting, and traversing elements - highlighting the more declarative style of functional programming.
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Philip Schwarz
(download for best quality slides) Gain a deeper understanding of why right folds over very large and infinite lists are sometimes possible in Haskell.
See how lazy evaluation and function strictness affect left and right folds in Haskell.
Learn when an ordinary left fold results in a space leak and how to avoid it using a strict left fold.
This version eliminates some minor imperfections and corrects the following two errors:
slide 15: "as sharing is required" should be "as sharing is not required"
slide 43: 푠푓표푙푑푙 (⊕) 푎 should be 푠푓표푙푑푙 (⊕) 푒
An array is a container that holds a fixed number of elements of the same type. An array's length is established at creation and cannot be changed. Each element has an index number starting from 0. The document demonstrates how to declare, initialize, access, and copy array elements in Java. It also discusses multidimensional arrays.
String objects are immutable in Java, so any operation that modifies a String value actually creates a new String object. The StringBuffer and StringBuilder classes provide mutable alternatives to String that have similar methods but do not create new objects with each modification. When a String literal value is used in code, it is stored in the String constant pool to promote reuse of these immutable objects.
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5Philip Schwarz
(download for best quality slides) Gain a deeper understanding of why right folds over very large and infinite lists are sometimes possible in Haskell.
See how lazy evaluation and function strictness affect left and right folds in Haskell.
Learn when an ordinary left fold results in a space leak and how to avoid it using a strict left fold.
Errata:
slide 15: "as sharing is required" should be "as sharing is not required"
slide 43: 𝑠𝑓𝑜𝑙𝑑𝑙 (⊕) 𝑎 should be 𝑠𝑓𝑜𝑙𝑑𝑙 (⊕) 𝑒
Stuck with your Ruby Programming Assignment. Get 24/7 help from tutors with Phd in the subject. Email us at support@helpwithassignment.com
Reach us at http://www.HelpWithAssignment.com
This document provides information about C++ classes and objects. It discusses arrays of class objects, static members and variables, const member functions, and string objects. It also includes examples of catching bugs in C++ code snippets and implementing classes for points, polygons, and rectangles.
This document discusses objects and classes in Java. It begins by defining what a class is - a template that defines common properties of objects. Everything in a Java program must be encapsulated within a class. A class defines an object's state via fields and behavior via methods. The document then discusses how to define classes by specifying fields, methods, and constructors. It provides examples of creating objects from classes and accessing object members. The document also covers key object-oriented programming concepts like encapsulation and inheritance.
This document provides an overview of key concepts in object-oriented programming in Java including classes, objects, methods, constructors, arrays, strings, and vectors. It defines classes as templates that define the data and behaviors of objects. Methods represent behaviors of classes. Constructors initialize objects. Arrays are containers that hold a fixed number of values of a single type. Strings are sequences of characters that can be manipulated using methods. Vectors are dynamic arrays that can grow or shrink as needed. The document includes examples of creating objects from classes, defining methods and constructors, declaring and initializing arrays, performing string operations, and using common vector methods.
This document provides instructions for exercises in an ECET 370 lab covering several topics:
1. Exercises 1-5 involve using or modifying binary search tree (BST) implementations to review BST concepts and properties.
2. Exercise 3 requires using a BST to implement a dictionary of Java keywords.
3. Exercise 4 involves writing a recursive algorithm to count nodes in a BST.
4. Exercise 5 requires writing an algorithm to find the maximum value in a BST.
This document provides an overview of object-oriented programming (OOP) concepts in Java, including classes, objects, inheritance, encapsulation, polymorphism, and dynamic binding. It explains the basic structure of a Java class, how to define methods and variables, and how to instantiate objects from classes. The document also discusses constructors and how to use inheritance to extend existing classes.
Infocampus Offers best Java training in Bangalore. Infocampus provides java classes with real time practical sessions. We are conducting weekdays and weekend classes and we have good infrastructure. Easy installments. 100% Placement assistance. Experienced trainers. If you are looking for training with placement assistance please do reach us @ 9738001024.visit: http://infocampus.co.in/java-training-bangalore.html
The document discusses basic object-oriented concepts in Java such as classes, objects, inheritance, and polymorphism. Some key points include:
- An object contains both data fields that represent its state and methods that operate on that data.
- A class defines the fields and methods common to all objects of that type. An object is an instance of a class.
- Inheritance allows subclasses to inherit and extend the functionality of parent classes. Subclass objects inherit all fields and methods of their parent classes.
- Methods can be overridden in subclasses to allow polymorphic behavior depending on an object's type. Sending a message to an object results in the execution of the corresponding method definition for that object's class.
The second programming assignment (HW4) is designed to help you ga.docxoreo10
The second programming assignment (HW4) is designed to help you gain
experience with object oriented programming in Java.
The given file for hw4, "hw4.given.tar.gz", is on the class web page.
To untar and unzip the file, execute
tar -xzvf hw4.given.tar.gz
It will expand to create a directory called hw4, which contains sub-
directories part0, ..., part9, one for each part of the assignment.
Each part has a Makefile. Don't modify them.
Main.java, which is different for each part, is used to test your code
by creating objects, invoking methods, etc.
As you did on the previous assignment, you'll be using the tester tool
for testing.
Proceed similarly to what you did on the previous programming
assignment:
cd part0
# add a bunch of code
make
# if make gives errors, fix them and make again.
../tester
# if tester gives errors, fix them and repeat this cycle.
In Part 7 (only), additional tests (in Main.java and correct output
files) check that the iterators' next() methods give an error if
they're invoked when no elements remain in their collection. (In
subsequent parts, such erroneous behavior results in an exception, so
the testing doesn't use these extra tests.)
Similar to the last assignment, each part builds off the last. When
you're finished with one part,
copy all .java files ***EXCEPT Main.java*** to the next part.
Then modify these copies to start your solution for the next part.
***Exception: again, don't copy Main.java from part to part.***
See the documentation on tester (on the class web page) for details on
its use.
As always, get started early to avoid the last minute rush!
ECS140A-F16-06 October 18, 2016
ASSIGNMENT 4: Java object oriented program
Due: October 27, 2016
Overview
The purpose of this assignment is for you to gain experience with object oriented programming in
Java: in particular, the ideas of inheritance, dynamic binding (virtual methods), overriding and
overloading methods, iterators (aka generators). It will also give you some exposure to how some
programming language features are implemented, i.e., what happens "behind the scenes" when
you execute a program. Although no language provides the exact features in this assignment, a
number of languages (e.g., Awk, Icon, LISP, CLU) do provide similar features. (In fact, you
could define a little language, using techniques from first program, that would contain features
like those in this assignment.)
Your program needs to provide several abstractions. The first abstraction is an Element, of which
there are three kinds: EBoolean, EInteger, and EString. The second abstraction is an EList of Ele-
ment; associated with the EList abstraction is EListIt, which iterates over a list. Details of these
are given below in each part of this assignment.
N.B., you are restricted as to how you write your code. See “Details” before you start coding.
1
ECS140A-F16-06 October 18, 20 ...
In this article we will learn classes and objects in C# programming.
Till now in the past two articles we have seen all the labs which was using functional programming. From now in coming all the articles we will do the programming using classes and objects. As this is professional approach of doing the programming. With classes and objects approach, code it reduces code reading complexity and it improves readability and also offers re-usability.
The document discusses self-referential structures in C. It begins by showing how a struct cannot directly contain a member of its own type, as this would cause infinite recursion. It then demonstrates how to make a struct self-referential by using a pointer to the struct as a member, rather than the struct itself. This allows the compiler to correctly allocate memory for the pointer. Linked lists are provided as an example application of self-referential structures. The document also covers dynamic memory allocation functions like malloc(), calloc(), free() and realloc() in C.
Getting Started - Console Program and Problem SolvingHock Leng PUAH
The document provides an introduction to variables in C#, including value types like integers and reference types like objects. It discusses defining and assigning values to variables, and differences between static and non-static classes. Examples show creating a basic console application in C# and reading input from the keyboard or command line. The document concludes with exercises that guide learning programming concepts like type conversion, calculating averages, and sorting integers.
The document provides an introduction to variables in C#, including value types like integers and reference types like objects. It discusses defining and assigning values to variables, and differences between static and non-static classes. Examples show creating a basic console application in C# and getting input from the user via arguments or keyboard. Exercises guide practicing variable usage, type conversion, and writing simple programs to calculate averages and swap values.
This document discusses basic object-oriented programming concepts. It explains that an object contains both data and methods that manipulate that data. An object represents a real-world entity and has state represented by its data fields. Classes describe objects and act as templates for creating multiple similar objects. Objects inherit characteristics from their classes and can override methods. Constructors are used to create and initialize new objects. Access control determines which parts of a class are visible and accessible to other classes.
This document provides an agenda and overview for a software construction class focusing on Java implementation. It covers several topics including enum types, memory allocation, object identity, equality, and copying. It discusses the Object class and methods like equals(), hashCode(), and clone() that can be overridden. Nested classes are also introduced. The document provides definitions and examples for key concepts.
The document discusses object-oriented concepts in Java including objects, classes, constructors, encapsulation, and Java source file layout. It defines objects as anything real or conceptual and classes as blueprints for objects. Constructors are special methods that initialize objects. Encapsulation hides implementation details and protects data using private attributes with public getters and setters. The Java source file layout follows a PIC order of package, import, classes. It also discusses creating JAR files to package related class files together.
The document discusses key concepts in object-oriented programming in Java including classes, objects, methods, constructors, and inheritance. Specifically, it explains that in Java, classes define the structure and behavior of objects through fields and methods. Objects are instances of classes that allocate memory at runtime. Methods define the behaviors of objects, and constructors initialize objects during instantiation. Inheritance allows classes to extend the functionality of other classes.
Similar to Building .NET-based Applications with C# (20)
ADO.NET Architecture
Data processing has traditionally relied primarily on a connection-based, two-tier model. As data
processing increasingly uses multi-tier architectures, programmers are switching to a
disconnected approach to provide better scalability for their applications.
LINQ
The acronym LINQ stands for Language Integrated Query. Microsoft’s query language is fully integrated and offers easy data access from in-memory objects, databases, XML documents, and many more. It is through a set of extensions, LINQ ably integrates queries in C# and Visual Basic. This tutorial offers a complete insight into LINQ with ample examples and coding. The entire tutorial is divided into various topics with subtopics that a beginner can be able to move gradually to more complex topics of LINQ.
10. Creating Windows-based Applications Part-I
Designing Forms: Using Common Controls, Using Container Controls, Creating Multiple Document
Interface (MDI) applications. Creating and using Main Menu, Toolbars, and Status Bar. Creating and Using
Common Dialog Boxes, Creating and Using Custom Dialog Boxes.
1. Examining Microsoft .NET Framework class library
2. The Object Browser
3. Overriding Methods from System.Object class
4. Formatting Strings, Numbers, Currency and date values.
5. Using Streams and Files: Read and Write both Binary and Text Files, Using FileStream
6. Serialization and De-serialization.
A matrix is a rectangular array of numbers arranged in rows and columns. There are several types of matrices including square, rectangular, diagonal, identity, and triangular matrices. Operations that can be performed on matrices include addition, subtraction, multiplication by a scalar, and determining the transpose, determinant, and inverse of a matrix. A C program is shown that uses nested for loops to input and output the elements of a matrix.
Using various data structures: Using Arrays (One Dimensional, Two Dimensional,
Jagged), Array.
ArrayList classes
Using Collections: Collection, HashTable, List, Stack, Queue, HashSet classes.
C# (This keyword, Properties, Inheritance, Base Keyword)Umar Farooq
The document discusses key object-oriented programming concepts in C#, including inheritance, encapsulation, and the use of the 'this' and 'base' keywords. Specifically:
1. It explains how the 'this' keyword is used to refer to properties and methods of the current class instance. It provides an example demonstrating accessing class variables vs local variables.
2. It describes properties in C# and how they are used to encapsulate data through getters and setters. Examples are given for read-write and read-only properties.
3. Inheritance is introduced as a fundamental OOP principle. The document defines inheritance and provides a code example demonstrating a base Shape class and derived Triangle class.
This document provides an overview of software process models. It defines a software process as a series of steps involving activities, constraints and resources to produce intended output. Key activities in the process include communicating with customers, identifying requirements, analyzing requirements, designing, developing, and testing software. Constraints and resources like people, software, hardware, equipment, time and money must also be considered. The document discusses fundamental activities in software processes like specification, development, validation and evolution. It also covers characteristics like understandability, visibility, supportability, acceptability, reliability and maintainability. Finally, it describes plan-driven and agile software process models and mentions various process models like waterfall, incremental, prototype, spiral and fountain models.
Assessment and Planning in Educational technology.pptxKavitha Krishnan
In an education system, it is understood that assessment is only for the students, but on the other hand, the Assessment of teachers is also an important aspect of the education system that ensures teachers are providing high-quality instruction to students. The assessment process can be used to provide feedback and support for professional development, to inform decisions about teacher retention or promotion, or to evaluate teacher effectiveness for accountability purposes.
Main Java[All of the Base Concepts}.docxadhitya5119
This is part 1 of my Java Learning Journey. This Contains Custom methods, classes, constructors, packages, multithreading , try- catch block, finally block and more.
Macroeconomics- Movie Location
This will be used as part of your Personal Professional Portfolio once graded.
Objective:
Prepare a presentation or a paper using research, basic comparative analysis, data organization and application of economic information. You will make an informed assessment of an economic climate outside of the United States to accomplish an entertainment industry objective.
How to Add Chatter in the odoo 17 ERP ModuleCeline George
In Odoo, the chatter is like a chat tool that helps you work together on records. You can leave notes and track things, making it easier to talk with your team and partners. Inside chatter, all communication history, activity, and changes will be displayed.
A review of the growth of the Israel Genealogy Research Association Database Collection for the last 12 months. Our collection is now passed the 3 million mark and still growing. See which archives have contributed the most. See the different types of records we have, and which years have had records added. You can also see what we have for the future.
Thinking of getting a dog? Be aware that breeds like Pit Bulls, Rottweilers, and German Shepherds can be loyal and dangerous. Proper training and socialization are crucial to preventing aggressive behaviors. Ensure safety by understanding their needs and always supervising interactions. Stay safe, and enjoy your furry friends!
हिंदी वर्णमाला पीपीटी, hindi alphabet PPT presentation, hindi varnamala PPT, Hindi Varnamala pdf, हिंदी स्वर, हिंदी व्यंजन, sikhiye hindi varnmala, dr. mulla adam ali, hindi language and literature, hindi alphabet with drawing, hindi alphabet pdf, hindi varnamala for childrens, hindi language, hindi varnamala practice for kids, https://www.drmullaadamali.com
A workshop hosted by the South African Journal of Science aimed at postgraduate students and early career researchers with little or no experience in writing and publishing journal articles.
This presentation was provided by Steph Pollock of The American Psychological Association’s Journals Program, and Damita Snow, of The American Society of Civil Engineers (ASCE), for the initial session of NISO's 2024 Training Series "DEIA in the Scholarly Landscape." Session One: 'Setting Expectations: a DEIA Primer,' was held June 6, 2024.
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Building .NET-based Applications with C#
1. C#Zone
Week 9(according to IUB outline):-
---------------------------------------------------------------------------------
9. Building .NET-based Applications with C#
1. Examining Microsoft .NET Framework class library
2. The Object Browser
3. Overriding Methods from System.Object class
4. Formatting Strings, Numbers, Currency and date values.
5. Using Streams and Files: Read and Write both Binary and Text Files, Using FileStream
6. Serialization and De-serialization.
---------------------------------------------------------------------------------
Any issue:umarfarooqworld@outlook.com
>>Welcome Back<<
2. Ref: C#Corner Pick “N” Share :C#Zone
2 | P a g e “A room without books is like a body without a soul”
1. Examining Microsoft .NET Framework class library
The .NET Framework class library is a library of classes, interfaces, and value types
that provide access to system functionality. It is the foundation on which .NET
Framework applications, components, and controls are built. The namespaces and
namespace categories in the class library are listed in the following table and
documented in detail in this reference. The namespaces and categories are listed by
usage, with the most frequently used namespaces appearing first.
There are Thousands of .NET Framework class libraries and some is mentioned
below:
Namespaces
Namespace Description
System
The System namespace contains fundamental classes and base classes that define commonly-
used Value and reference data types, events and event handlers, interfaces, attributes, and
processing exceptions.
System.Collections The System.Collections namespaces contain types that define various standard, specialized,
and generic collection objects.
2. Using the Object Browser
Visual C# 2008 includes a useful tool that enables you to easily view members (properties,
methods, and events) of all the objects in a project: the Object Browser (see Figure 3.10).
This is useful when dealing with objects that aren’t well documented because it enables you
to see all the members an object supports. To view the Object Browser, choose View, Other
Windows, Object Browser from the menu.
3. Ref: C#Corner Pick “N” Share :C#Zone
3 | P a g e “A room without books is like a body without a soul”
Figure 3.10. The Object Browser enables you to view all properties and methods of
an object.
The Browse drop-down list in the upper-left corner of the Object Browser is used to
determine the browsing scope. You can choose My Solution to view only the objects
referenced in the active solution, or you can choose All Components to view all possible
objects. You can customize the object set by clicking the drop-down arrow next to the
Object Browser Settings button to the far right of the Browse drop-down list. I
don’t recommend changing the custom object setting until you have some experience using
Visual C# objects as well as experience using the Object Browser.
The top-level nodes (each item in the tree is referred to as a node) in the Objects tree are
libraries. Libraries are usually DLL or EXE files on your computer that contain one or more
objects. To view the objects within a library, simply expand the library node. As you select
objects within a library, the list to the right of the Objects tree shows information regarding
the members of the selected object (refer to Figure 3.10). For even more detailed
information, click a member in the list on the right, and the Object Browser shows
information about the member in the area below the two lists.
4. Ref: C#Corner Pick “N” Share :C#Zone
4 | P a g e “A room without books is like a body without a soul”
3. Overriding Methods from System.Object class
Introduction:
Let us start by creating a new class and we will leave it with out any methods.
public class Employee
{
}
In the next step we will try to use our class, we will find that our Employee class contains 4 methods
which are (Equals, GetHashCode, GetType, and ToString).
The question now, from where these four methods come from?
The answer is easy: any data type in the .Net inherits implicitly from the Object class which defines a
common set of members supported by every type in the .NET, so when we create our new class
Employee it inherits from the Object class.
The Object base class defines some members that are virtual so it allows us to redefine the default
implementation of these members.
These virtual members give you a good work, but in some cases you will need a new
implementation of these methods to fit your class functionality.
In the next section we will see how to use the default implementation of the Object class virtual
methods and then we will try to redefine it by using override keyword to give it a new behavior.
5. Ref: C#Corner Pick “N” Share :C#Zone
5 | P a g e “A room without books is like a body without a soul”
ToString() Method:
The ToString() method gives you a textual representation of the current state of the object.
Example:
namespace UsingObjectClass
{
public class Employee
{
string firstName;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
string lastName;
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
int age;
public int Age
{
get { return age; }
set { age = value; }
}
string employeeID;
public string EmployeeID
{
get { return employeeID; }
set { employeeID = value; }
}
}
class Program
{
static void Main(string[] args)
{
Employee emp1 = new Employee();
emp1.FirstName = "Amr";
emp1.LastName = "Ashush";
emp1.Age = 23;
string s = emp1.ToString();
Console.WriteLine(s);
}
}
}
6. Ref: C#Corner Pick “N” Share :C#Zone
6 | P a g e “A room without books is like a body without a soul”
The result:
As you can see the returned string is the name of the Employee Type (UsingObjectClass.Employee).
What if we want to use the ToString() method to show the current employee data (First Name, Last
Name, and Age).
All we need to do is to override the ToString() Method to give it a new behavior, so in our case we will
redefine it to show the Employee data instead of the name of the object type.
Overriding ToString() Method:
The first step is to use the override keyword to override the method and then we will redefine its
behavior.
Example:
public class Employee
{
....
//Overriding ToString() method
public override string ToString()
{
string s = "First Name: " + firstName + " , " + " last Name: " + lastName + " , " +"and Age: " +
age;
return s;
}
}
Trying the new behavior of the ToString() method:
Employee emp1 = new Employee();
emp1.FirstName = "Amr";
emp1.LastName = "Ashush";
emp1.Age = 23;
string s = emp1.ToString();
Console.WriteLine(s);
7. Ref: C#Corner Pick “N” Share :C#Zone
7 | P a g e “A room without books is like a body without a soul”
The result:
As you can see we now have a good text representation of our object.
We can use also StringBuilder in our ToString() method as follow:
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("First Name: {0}, Last Name: {1}, and Age: {2}", firstName, lastName, age);
return sb.ToString();
}
Equals() Method:
Equals() method is used to compare two objects and it returns a true if these objects point to the same
values on the heap and returns false if not.
Example:
Employee emp1 = new Employee();
emp1.FirstName = "Amr";
emp1.LastName = "Ashush";
emp1.Age = 23;
Employee emp2 = emp1;
We now have two objects that point to the same value on the heap, so if we tried to use Equals()
method it will return true.
//this will return True.
emp1.Equals(emp2);
Now we will create two objects each one has its own value on the heap, so when we use Equals()
method it will return False.
Employee emp3 = new Employee();
emp3.FirstName = "Amr";
emp3.LastName = "Ashush";
emp3.Age = 40;
emp3.EmployeeID = "123A";
8. Ref: C#Corner Pick “N” Share :C#Zone
8 | P a g e “A room without books is like a body without a soul”
Employee emp4 = new Employee();
emp4.FirstName = "Amr";
emp4.LastName = "Ashush";
emp4.Age = 23;
emp4.EmployeeID = "123A";
//this will return False.
emp3.Equals(emp4);
Overriding Equals() Method:
Consider that we want to compare two objects but we do not want to know if these objects pointing to
the same value in the heap, all we need to know that if these two objects have the same data like
(First Name, and Last Name) for example.
Example:
//Overriding Equals() method
public override bool Equals(object obj)
{
if (obj != null && obj is Employee)
{
Employee emp = (Employee)obj;
if (emp.firstName == this.firstName &&
emp.lastName == this.lastName &&
emp.employeeID == this.employeeID)
return true;
}
return false;
}
Now when we try to use the Equals() method it will compare the firstName, lastName, and employeeID
of the two objects and it will return true if these value are the same and false if not.
Example:
Employee emp1 = new Employee();
emp1.FirstName = "Amr";
emp1.LastName = "Ashush";
emp1.Age = 23;
emp1.EmployeeID = "123A";
Employee emp2 = new Employee();
emp2.FirstName = "Amr";
emp2.LastName = "Ashush";
emp2.Age = 23;
emp2.EmployeeID = "123A";
//this will return True.
emp1.Equals(emp2);
If we have two objects with different data Equals method will return false.
Employee emp3 = new Employee();
emp3.FirstName = "Jack";
emp3.LastName = "Baher";
emp3.Age = 40;
emp3.EmployeeID = "1254B";
9. Ref: C#Corner Pick “N” Share :C#Zone
9 | P a g e “A room without books is like a body without a soul”
Employee emp4 = new Employee();
emp4.FirstName = "James";
emp4.LastName = "Bond";
emp4.Age = 23;
emp4.EmployeeID = "007";
//this will return False.
emp3.Equals(emp4);
GetHashCode() Method:
The GetHashCode() method is used to return a numerical value that identefies an object based on its
internal data.
Example:
Employee emp1 = new Employee();
emp1.FirstName = "Numan";
emp1.LastName = "Ashraf";
emp1.Age = 23;
emp1.EmployeeID = "125";
Employee emp2 = new Employee();
emp2.FirstName = "Ali";
emp2.LastName = "Hashmi";
emp2.Age = 23;
emp2.EmployeeID = "125";
Console.WriteLine("emp 1 hash code: {0}", emp1.GetHashCode());
Console.WriteLine("emp 2 hash code: {0}", emp2.GetHashCode());
the result will be:
emp 1 hash code: 45653674
emp 2 hash code: 41149443
As you can see, instead of the two objects have the same data, each one have different hash code
because each object points to a different place on the heap.
So if we create two objects that point to the same value, when we call GetHashCode() method from
any one we will get the same hash code.
Example:
Employee emp1 = new Employee();
emp1.FirstName = "Numan";
emp1.LastName = "Ashraf";
emp1.Age = 23;
emp1.EmployeeID = "125";
Employee emp2 = emp1;
Console.WriteLine("emp 1 hash code: {0}", emp1.GetHashCode());
Console.WriteLine("emp 2 hash code: {0}", emp2.GetHashCode());
the result will be:
emp 1 hash code: 45653674
emp 2 hash code: 45653674
10. Ref: C#Corner Pick “N” Share :C#Zone
10 | P a g e “A room without books is like a body without a soul”
Overriding GetHashCode() Method:
We need to override GetHashCode() method so if we have two objects with identical data we will
obtain the same hash code.
The String class has its own implementation of GetHashCode() method based on the string's character
data.
We can use the string that return from the overriden ToString() method and use it to call
GetHashCode() method. So if we have two objects with the same First Name, Last Name, and Age we
will obtain the same hash code.
//Overriding the GetHashCode method
public override int GetHashCode()
{
return ToString().GetHashCode();
}
Example:
Employee emp1 = new Employee();
emp1.FirstName = "Numan";
emp1.LastName = "Ashraf";
emp1.Age = 23;
emp1.EmployeeID = "125";
Employee emp2 = new Employee();
emp2.FirstName = "Numan";
emp2.LastName = "Ashraf";
emp2.Age = 23;
emp2.EmployeeID = "125";
Console.WriteLine("emp 1 hash code: {0}", emp1.GetHashCode());
Console.WriteLine("emp 2 hash code: {0}", emp2.GetHashCode());
the result will be:(the same hash code)
emp 1 hash code: -1503318716
emp 2 hash code: -1503318716
As you can see we get the same hash code although we have two object that are point to different
values on the heap.
Another option is to identify a string field that should be unique among objects and then return its hash
code.
In our case EmployeeID suould be unique so if we have two object with the same EmployeeID we will
get the same hash code.
//Overriding the GetHashCode method
public override int GetHashCode()
{
return EmployeeID.GetHashCode();
}
Note: Overriding GetHashCode() method only useful when you want to store your object in hash-
based collection such as Hashtable beacause the Hashtable type calles the Equals() and GetHashCode()
methods of the contained objects under the hood to determine the correct object to return to the
caller. and the Object class has no idea about the data on its subclasses.
11. Ref: C#Corner Pick “N” Share :C#Zone
11 | P a g e “A room without books is like a body without a soul”
4. Formatting Strings, Numbers, Currency and date values.
The Syntax of the String.Format() Method
The general syntax of the String.Format() method is as follows:
String.Format("format string", arg1, arg2, .... );
The format string is the string into which the values will be placed. Within this string
are place holders which indicate the location of each value within the string. Place holders
take the form of braces surrounding a number indicating the corresponding argument to be
substituted for the place holder. Following on from the format string is a comma separated
list of arguments. There must be an argument for each of the place holders.
A Simple C# String Format Example
The following code fragment demonstrates a very simple use of the String.Format() method:
string newString;
newString = String.Format("There are {0} cats in my {1} and no {2}", 2, "house", "dogs");
System.Console.WriteLine (newString);
When run, the above code will result in the following output:
There are 2 cats in my house and no dogs
Let's quickly review the String.Format() method call. The format string contains 3 place holders
indicated by {0}, {1} and {2}. Following the format string are the arguments to be used in each
place holder. For example, {0} is replaced by the first argument (the number 2), the {1} by the
second argument (the string "house") and so on.
12. Ref: C#Corner Pick “N” Share :C#Zone
12 | P a g e “A room without books is like a body without a soul”
Formatting Dates and Times in C#
There are number of techniques available for extracting and displaying dates and times in
particular formats. Output may be configured using a small number of predefined formatting
methods or customized with an almost infinite number of variations using the ToString()
method.
The basic formatting methods operate as follows:
DateTime meetingAppt = new DateTime(2008, 9, 22, 14, 30, 0);
System.Console.WriteLine(meetingAppt.ToLongDateString()); // Monday, September 22, 2008
System.Console.WriteLine(meetingAppt.ToShortDateString()); // 9/22/2008
System.Console.WriteLine(meetingAppt.ToShortTimeString()); // 2:30 PM
If the above prepackaged formatting methods do not provide the required output, a formidable
variety of custom formats may be constructing using the ToString() method.
The ToString() method takes as an argument a format string which specifies precisely how the
date and time is to be displayed. The following example shows a few of this formats in action.
The subsequent table lists all the possible format variables which may be used:
DateTime meetingAppt = new DateTime(2008, 9, 22, 14, 30, 0);
System.Console.WriteLine(meetingAppt.ToString("MM/dd/yy")); // 09/22/08
System.Console.WriteLine(meetingAppt.ToString("MM - dd - yyyy")); // 09 - 22 - 2008
System.Console.WriteLine(meetingAppt.ToString("ddd dd MMM yyyy")); // Mon 22 Sep 2008
System.Console.WriteLine(meetingAppt.ToString("dddd dd MMMM yyyy")); // Monday September 22 2008
The full list of format patterns support by the ToString() method of the C# DateTime class is as
follows:
Format
Specifier
Description
d The day of the month. Single-digit days will not have a leading zero.
dd The day of the month. Single-digit days will have a leading zero.
ddd
The abbreviated name of the day of the week, as defined in
AbbreviatedDayNames.
dddd The full name of the day of the week, as defined in DayNames.
M The numeric month. Single-digit months will not have a leading zero.
MM The numeric month. Single-digit months will have a leading zero.
MMM The abbreviated name of the month, as defined in AbbreviatedMonthNames.
MMMM The full name of the month, as defined in MonthNames.
13. Ref: C#Corner Pick “N” Share :C#Zone
13 | P a g e “A room without books is like a body without a soul”
Currency
In this article we will learn how to display a number in its currency format with respect to a
country. When we want to display a number in its respective country's currency format, we
format the string in the currency format and get the currency symbol of a specific country
using the "CultureInfo" class available in .Net. To use the CultureInfo class, we need to
include the "System.Globalization" Namespace in our program.
The "C" format specifier converts a number to a string that represents a currency amount.
The precision specifier indicates the desired number of decimal places in the result string. If
the precision specifier is omitted then the default precision is used (the default value is 2).
If the value to be formatted has more than the specified or the default number of decimal
places then the fractional value is rounded in the result string. If the value to the right of
the number of the specified decimal places is 5 or greater then the last digit in the result
string is rounded away from zero.
Here is code showing how to convert a number to its corresponding currency format for a respective country:
using System;
using System.Globalization;
namespace CurrencyFormatter
{
class Program
{
static void Main(string[] args)
{
double value = 5623345.6789;
//For Current Culture
Console.WriteLine("n--------- Displaying Currency in Current Culture ---------------n");
// By default, single letter C displays currency upto two decimal digits
Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture));
// C2 displays currency upto two digits
Console.WriteLine(value.ToString("C2", CultureInfo.CurrentCulture));
// C3 displays currency upto three digits
Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture));
// C4 displays currency upto four digits
Console.WriteLine(value.ToString("C4", CultureInfo.CurrentCulture));
// C5 displays currency upto five digits
Console.WriteLine(value.ToString("C5", CultureInfo.CurrentCulture));
14. Ref: C#Corner Pick “N” Share :C#Zone
14 | P a g e “A room without books is like a body without a soul”
//For Japan
Console.WriteLine("n--------- Dispalying Currency for Japan ---------------n");
Console.WriteLine(value.ToString("C", CultureInfo.CreateSpecificCulture("ja-JP")));
//For Denmark
Console.WriteLine("n--------- Dispalying Currency for Denmark ---------------n");
Console.WriteLine(value.ToString("C",CultureInfo.CreateSpecificCulture("da-DK")));
//For India
Console.WriteLine("n--------- Dispalying Currency for India ---------------n");
Console.WriteLine(value.ToString("C",CultureInfo.CreateSpecificCulture("en-IN")));
Console.Read();
}
}
}
15. Ref: C#Corner Pick “N” Share :C#Zone
15 | P a g e “A room without books is like a body without a soul”
Numbers
Number of time the end user / client require to display numeric data in different format. In this post I am going
to discuss about the various type of the custom format that provided by C#.net to achieve requirement. Here I
am going to discuss each format one by one..
"0" Custom Specifier
ToString("00000") - format put the leading 0 when number get display if digits in number less than the number
of zero specified. when the below code is get executed output display 01234 because the number of digit less
than the number of zero.
double value;
value = 1234;
Console.WriteLine("Format 1: " + value.ToString("00000"));
Console.WriteLine();
ToString("00.00") - format do same thing as above replace zero if the number digit less , but the zero after
decimal point allows to display digit equals number of zero after decimal if the number of digit less than display
zero in place of that. output of the following code is 01.24 i.e only 2 digit allowed after decimal point. Note : -
decimal point is display as per specified culture.
value = 1.235;
Console.WriteLine("Format 2: " + value.ToString("00.00",CultureInfo.InvariantCulture));
Console.WriteLine();
ToString("0,0") - format cause to display comma between number. here when the following code is get
executed , is get display after every three digit 1,234,567,890. Note : - in this comma get replace by the culture.
value = 1234567890;
Console.WriteLine("Format 3: " + value.ToString("0,0",CultureInfo.InvariantCulture));
Console.WriteLine();
ToString("0,0.0") - format is combination of above format.
value = 1234567890.123456;
Console.WriteLine("Format 4: " + value.ToString("0,0.0",CultureInfo.InvariantCulture));
Console.WriteLine();
Output
16. Ref: C#Corner Pick “N” Share :C#Zone
16 | P a g e “A room without books is like a body without a soul”
5. Using Streams and Files: Read and Write both Binary and
Text Files, Using FileStream
Introduction
In memory, objects cease to exist when a program ends. But files exist until deletion. With files we persist data.
A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for
reading or writing, it becomes a stream. The stream is basically a sequence of bytes passing through the
communication path. There are two main streams, the input stream and the output stream.
The input stream is used for reading data from a file (read operation) and the output stream is used for writing
into the file (write operation). We handle them with types in System.IO.
Various Types of C# I/O Classes
The System.IO namespace has various classes for performing various operation with files, like creating and
deleting files, reading from or writing to a file, closing a file and so on.
Some important classes are as follows:
I/O Class Description
FileStream Used to read from and write to any location in a file
BinaryReader Reads primitive data from a binary stream
BinaryWriter Writes primitive data in binary format
File Use for manipulating files
StreamReader Used for reading characters from a byte stream
StreamWriter Is used for writing characters to a stream
StringReader Is used for reading from a string buffer
StringWriter Is used for writing into a string buffer
Directory Helps in manipulating a directory structure
DirectoryInfo Used for performing operations on directories
Now we see examples of some important I/O class and examine the outputs.
The FileStream Class
The FileStream class in the System.IO namespace helps in reading from, writing to and closing files. This class
derives from the abstract class Stream. You need to create a FileStream object to create a new file or open an
existing file. The syntax for creating a FileStream object is as follows:
1. FileStream <object_name> = new FileStream( <file_name>,<FileMode Enumerator>, <FileAccess Enumerat
or>, <FileShare Enumerator>);
For example, create a FileStream object F for reading a file named Example.txt as:
1. FileStream My_File = new FileStream("Example.xlsx", FileMode.Open, FileAccess.ReadWrite, FileShare
.ReadWrite);
17. Ref: C#Corner Pick “N” Share :C#Zone
17 | P a g e “A room without books is like a body without a soul”
Now we see the meaning of each parameter.
FileMode
The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator
are:
Mode Description
Append It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist
Create It creates a new file. If file is already exist then it will overrite that file
CreateNew It will also use to create a new file If the file is already exist then it will throw an Exception
Open It opens an existing file
OpenOrCreate
It specifies to the operating system that it should open a file if it exists, otherwise it should create a new
file
Truncate It opens an existing file and truncates its size to zero bytes
FileAccess
The FileAccess enumerator defines the kind of task to do with the file.
AccessMode Description
Read Data can be write from file
Write Data can be write written to the file
ReadWrite Data can be written to and read from the file
FileShare
This enumerator applies the type of permission for sharing.
SharingMode Description
Inheritable It allows a file handle to pass inheritance to the child processes
None It declines sharing of the current file
Read It allows opening the file for reading
ReadWrite It allows opening the file for reading and writing
Write It allows opening the file for writing
Example
The following program shows the use of the FileStream class:
18. Ref: C#Corner Pick “N” Share :C#Zone
18 | P a g e “A room without books is like a body without a soul”
Stream Reader and Stream Writer
The StreamReader and StreamWriter classes are used for reading from and writing data to text files. These
classes inherit from the abstract base class Stream that supports reading and writing bytes into a file stream.
The StreamReader Class
The StreamReader class also inherits from the abstract base class TextReader that represents a reader for
reading series of characters. The following table describes some of the commonly used methods of the
StreamReader class:
Method Name Description
public override void
Close()
It closes the StreamReader object and the underlying stream and releases any system resources
associated with the reader.
public override int
Peek()
Returns the next available character but does not consume it
public override int
Read()
Reads the next character from the input stream and advances the character position by one
character
The StreamWriter Class
The StreamWriter class inherits from the abstract class TextWriter that represents a writer that can write a
series of characters.
The following table shows some of the most commonly used methods of this class:
Method Description
public override void Close() Closes the current StreamWriter object and the underlying stream
public override void Flush()
Clears all buffers for the current writer and causes any buffered data to be written to
the underlying stream
public virtual void Write(bool
value)
Writes the text representation of a Boolean value to the text string or stream.
(Inherited from TextWriter.)
public override void Write( char
value )
Writes a character to the stream
public virtual void Write( decimal
value )
Writes the text representation of a decimal value to the text string or stream
public virtual void Write( double
value )
Writes the text representation of an 8-byte floating-point value to the text string or
stream
public virtual void Write( int
value )
Writes the text representation of a 4-byte signed integer to the text string or stream
public override void Write( string
value )
Writes a string to the stream
public virtual void WriteLine() Writes a line terminator to the text string or stream
19. Ref: C#Corner Pick “N” Share :C#Zone
19 | P a g e “A room without books is like a body without a soul”
Example
The following example shows writing text data into a file using the StreamWriter class:
Binary Reader and Binary Writer
The BinaryReader and BinaryWriter classes are used for reading from and writing to a binary file.
The BinaryReader Class
The BinaryReader class is used to read binary data from a file. A BinaryReader object is created by passing
a FileStream object to its constructor.
The following table shows some of the commonly used methods of the BinaryReader class:
Method Description
public override void
Close()
It closes the BinaryReader object and the underlying stream
public virtual int Read()
Reads the characters from the underlying stream and advances the current position of the
stream
public virtual bool
ReadBoolean()
Reads a Boolean value from the current stream and advances the current position of the
stream by one byte
public virtual char
ReadChar()
Reads the next character from the current stream and advances the current position of the
stream in accordance with the Encoding used and the specific character being read from the
stream
public virtual char[]
ReadChars( int count )
Reads the specified number of characters from the current stream, returns the data in a
character array and advances the current position in accordance with the Encoding used and
the specific character being read from the stream
public virtual string
ReadString()
Reads a string from the current stream. The string is prefixed with the length, encoded as an
integer seven bits at a time
20. Ref: C#Corner Pick “N” Share :C#Zone
20 | P a g e “A room without books is like a body without a soul”
The BinaryWriter Class
The BinaryWriter class writes binary data to a stream. A BinaryWriter object is created by passing a FileStream
object to its constructor.
The following table shows some of the commonly used methods of the BinaryWriter class:
Method Description
public override void
Close()
It closes the BinaryWriter object and the underlying stream
public virtual long Seek(
int offset, SeekOrigin
origin )
Sets the position within the current stream
public virtual void Write(
byte[] buffer )
Writes a byte array to the underlying stream
public virtual void Write(
char ch )
Writes a Unicode character to the current stream and advances the current position of the
stream in accordance with the Encoding used and the specific characters being written to
the stream
public virtual void Write(
char[] chars )
Writes a character array to the current stream and advances the current position of the
stream in accordance with the Encoding used and the specific characters being written to
the stream
public virtual void Write(
string value )
Writes a length-prefixed string to this stream in the current encoding of the BinaryWriter
and advances the current position of the stream in accordance with the encoding used and
the specific characters being written to the stream
Example 1
21. Ref: C#Corner Pick “N” Share :C#Zone
21 | P a g e “A room without books is like a body without a soul”
Example 2
Let us see another example that will clarify the concepts.
1. static void Main(string[] args)
2. {
3. string FILE_NAME = "Test_File.data";
4. // Create the new, empty data file.
5. if (File.Exists(FILE_NAME))
6. {
7. Console.WriteLine("{0} is already exists!", FILE_NAME);
8. Console.WriteLine("Please Give Another Name");
9. return;
10. }
11. using (FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew))
12. {
13. // Create the writer for data.
14. using (BinaryWriter w = new BinaryWriter(fs))
15. {
16. // Write data to Test.data.
17. for (int i = 0; i < 20; i++)
18. {
19. w.Write(i);
20. }
21. }
22. }
23. // Create the reader for data.
24. using (FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read))
25. {
26. using (BinaryReader r = new BinaryReader(fs))
27. {
28. // Read data from Test.data.
29. for (int i = 0; i < 20; i++)
30. {
31. Console.WriteLine(r.ReadInt32());
32. }
33. }
34.
35. Console.ReadKey();
36. }
Output
I hope this article help you learn about File I/O in C#.
22. Ref: C#Corner Pick “N” Share :C#Zone
22 | P a g e “A room without books is like a body without a soul”
6. Serialization and De-serialization
Serialization
Sometimes, you might want to store a collection of objects to a file and then read them back in
your program. For example, a collection of objects that represents a group of students in a class
have to be stored in a file. These objects will be used later in the program.
Serialization is the process of writing an object to a file. In contrast, deserialization reads the
object back from the file. An object that is serializable must be marked
with Serializable keyword.
In C#, you can use the BinaryFormatter class (in
System.Runtime.Serialization.Formatters.Binary namespace) to write an object to a file and read
the object from the file. To write the object to the file, you will use its Serialize method. The
Serialize method takes two arguments. One argument is the stream object representing the file
that the object will be stored and another argument is the object. Its Deserialize method will
read the object back from the file. It accepts one argument that is the stream object representing
the file to be read from. In the example below, the Student class is marked with the Serializable
keyword so that it can be serialized. The writeObject method can be called to write a student
object to a file. The readObject method will read the object back.
[Serializable()]
class Student
{
private string id;
private string name;
public Student(string id, string name)
{
this.id = id;
this.name = name;
}
public string pid
{
get { return id;}
set { id=value;}
}
public string pname
{
get { return name; }
set { name = value; }
}
}
23. Ref: C#Corner Pick “N” Share :C#Zone
23 | P a g e “A room without books is like a body without a soul”
static void writeObject(string path)
{
FileStream fs = null;
ArrayList al = new ArrayList() ;
try
{
fs = new FileStream(path, FileMode.Create, FileAccess.Write);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, new Student("999", "Dara"));
}
catch (Exception e) { Console.WriteLine(e.Message); }
finally
{
fs.Close();
}
}
static void readObject(string path)
{
FileStream fs = null;
try
{
fs = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryFormatter bf = new BinaryFormatter();
Student st =(Student) bf.Deserialize(fs);
Console.WriteLine("Id={0}, Name={1}",st.pid,st.pname);
}
catch (Exception e) { Console.WriteLine(e.Message); }
finally
{
fs.Close();
}
}
If you want to store a collection of many objects in a file, you need to package the objects in an
ArrayList. Then write the ArrayList object to the file.
Example:
ArrayList al=new ArrayList();
fs = new FileStream(path, FileMode.Create, FileAccess.Write);
BinaryFormatter bf = new BinaryFormatter();
al.Add(new Student("0999", "Dara"));
al.Add(new Student("888", "Yuk"));
Simply, you can read the ArrayList object that contains the student objects as shown below:
ArrayList al = (ArrayList)bf.Deserialize(fs)
24. Ref: C#Corner Pick “N” Share :C#Zone
24 | P a g e “A room without books is like a body without a soul”
Complete Code-Example
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace SerializationDemo
{
[Serializable()]
class Student
{
private string id;
private string name;
public Student(string id, string name)
{
this.id = id;
this.name = name;
}
public string pid
{
get { return id;}
set { id=value;}
}
public string pname
{
get { return name; }
set { name = value; }
}
}
class Program
{
static void writeObject(string path)
{
FileStream fs = null;
ArrayList al = new ArrayList() ;
try
{
fs = new FileStream(path, FileMode.Create, FileAccess.Write);
BinaryFormatter bf = new BinaryFormatter();
//al.Add(new Student("0999", "Dara"));
//al.Add(new Student("888", "Yuk"));
bf.Serialize(fs, new Student("0999", "Dara"));
}
catch (Exception e) { Console.WriteLine(e.Message); }
finally
{
fs.Close();
}
}
25. Ref: C#Corner Pick “N” Share :C#Zone
25 | P a g e “A room without books is like a body without a soul”
static void readObject(string path)
{
FileStream fs = null;
try
{
fs = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryFormatter bf = new BinaryFormatter();
Student st =(Student) bf.Deserialize(fs);
Console.WriteLine("Id={0}, Name={1}",st.pid,st.pname);
//ArrayList al = (ArrayList)bf.Deserialize(fs);
//Student st = (Student)al[0];
//Console.WriteLine(st.pid);
}
catch (Exception e) { Console.WriteLine(e.Message); }
finally
{
fs.Close();
}
}
static void Main(string[] args)
{
writeObject("d:/students.bin");
readObject("d:/students.bin");
Console.Read();
}
}
}