Windows form application using System.Windows.Forms; using System.Drawing; class MyForm:Form{ public static void Main(){ Application.Run(new.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

2. C# Language Fundamentals
Procedural Programming in C# Chapters Objectives You will be able to: Describe the most important data types available in C#. Read numeric values.
IT 325 OPERATING SYSTEM C programming language. Why use C instead of Java Intermediate-level language:  Low-level features like bit operations  High-level.
ARDUINO CLUB Session 1: C & An Introduction to Linux.
2 nd Semester Selection Statement Computer and Programming (204111)
Air Force Institute of Technology Electrical and Computer Engineering
C# Language Report By Trevor Adams. Language History Developed by Microsoft Developed by Microsoft Principal Software Architect Principal Software Architect.
Computer and Programming
8-May-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Java Planning our Programs Flowcharts Arithmetic Operators.
Getting Started with C# 1 SWE 344 Internet Protocols & Client Server Programming.
INSTRUCTOR: SHIH-SHINH HUANG Windows Programming Using Java Chapter4: Control Statements Part I.
Shlomo Hershkop1 Introduction to java Class 1 Fall 2003 Shlomo Hershkop.
 2002 Prentice Hall. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 The if Selection Structure.
Introduction to Computers and Programming Lecture 7:
16-Jun-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Basic Elements of C++ Chapter 2.
An Introduction to C Programming Geb Thomas. Learning Objectives Learn how to write and compile a C program Learn what C libraries are Understand the.
Tutorial C#. PLAN I. Introduction II. Example of C# program :Hello World III. How to use C# language GUI elements Primitives Types Expressions and operators.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chapter 3: Data Types and Operators JavaScript - Introductory.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
LESSON 6 – Arithmetic Operators
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
CSCI 3328 Object Oriented Programming in C# Chapter 5: C# Control Statement – Part II UTPA – Fall
Windows Programming, C.-S. Shieh, KUAS EC, Chapter 3 Operators and Expressions.
Semester Review. As we have discussed, Friday we will have in class time for you to work on a program, this program will come with instructions and you.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 2 Basic Elements of Java.
1 Java Programming 1 Introduction to Basic GUI Lesson 4.
An Introduction to Java – Part 1 Dylan Boltz. What is Java?  An object-oriented programming language  Developed and released by Sun in 1995  Designed.
Data Types and Operators  Two category of data types:  Primitive type: value type. Store values.  Object type: reference type. Store addresses.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1.
1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 The if Selection Structure 4.6 The if / else Selection Structure 4.7.
1 Programming Java Java Basics. 2 Java Program Java Application Program Application Program written in general programming language Applet Program running.
C Operators. CONTENTS C OPERATORS TYPES OF OPERATOR UNARY BINARY TERNARY ARITHMATIC RELATIONAL LOGICAL.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
SE-1010 Dr. Mark L. Hornick 1 Variables & Datatypes.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
Conditional Expressions
PHY-102 SAPVariables and OperatorsSlide 1 Variables and Operators In this section we will learn how about variables in Java and basic operations one can.
1-Dec-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
C++ Basics. Compilation What does compilation do? g++ hello.cpp g++ -o hello.cpp hello.
C# Operator Overloading and Type Conversions C#.NET Software Development Version 1.0.
OperatorstMyn1 Operators An operator is something that you feed with one or more values (or expressions, in programming jargon) which yields another value.
Introduction to Computers and Programming Lecture 7:
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Lecturer: Nguyen Thi Hien Software Engineering Department Home page: hienngong.wordpress.com Chapter 2: Language C++
The ++ and -- expressions. The ++ and -- operators You guessed it: The ++ and -- are operators that return a value.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103 material developed.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
CompSci 230 S Programming Techniques
CSC111 Quick Revision.
Today’s topic: Arithmetic expressions.
Computing with C# and the .NET Framework
Chapter 4 – Control Structures Part 1
Java Programming: From Problem Analysis to Program Design, 4e
SELECTION STATEMENTS (1)
Tutorial C#.
Introduction to Programming in Java
OPERATORS (2) CSC 111.
Starting JavaProgramming
An Introduction to Java – Part I, language basics
elementary programming
The important features of OOP related to C#:
Additional control structures
Presentation transcript:

Windows form application

using System.Windows.Forms; using System.Drawing; class MyForm:Form{ public static void Main(){ Application.Run(new MyForm()); } protected override void OnPaint(PaintEventArgs e){ e.Graphics.DrawString("Hello World!", new Font("Arial", 35), Brushes.Blue, 10, 100); }

 The source code in Figure 1 ‑ 1 displays the text "Hello World!" in a window. (The C# version of a command line hello-world application would be a one-liner). As you can see from the code, C# has a C-based syntax, but with objects like C++ or Java. Every function in C# is a method of a type.  In this example, the MyForm class is defined to derive its functionality from the Form class (part of the.NET Framework Class Library). In addition it defines two new methods, Main() and OnPaint().  All C# (or.NET) applications must have a static method named Main() defined to be the entry point of the application.

 The static Main() method can be defined in any class in the application, so long as its name is “Main” and it is declared to be static.  The OnPaint() method is an override of a virtual method on the Form class. It is called when the window needs to paint itself. This sample uses this method to draw the text "Hello World!".  Most of the code in Figure 1 ‑ 1 will be covered in detail throughout this text. Don’t worry too much about the parts that don’t make sense right now. However, I would take the time to look the code over, perhaps build and run it, and get a feel for the sample.

Basics of C#

Array

using System; class Array { public static void Main() { int[] myInts = { 5, 10, 15 }; bool[][] myBools = new bool[2][]; myBools[0] = new bool[2]; myBools[1] = new bool[1]; double[,] myDoubles = new double[2, 2]; string[] myStrings = new string[3]; Console.WriteLine("myInts[0]: {0}, myInts[1]: {1}, myInts[2]: {2}", myInts[0], myInts[1], myInts[2]); myBools[0][0] = true; myBools[0][1] = false; myBools[1][0] = true; Console.WriteLine("myBools[0][0]: {0}, myBools[1][0]: {1}", myBools[0][0], myBools[1][0]); myDoubles[0, 0] = 3.147; myDoubles[0, 1] = 7.157; myDoubles[1, 1] = 2.117; myDoubles[1, 0] = ; Console.WriteLine("myDoubles[0, 0]: {0}, myDoubles[1, 0]: {1}",myDoubles[0, 0], myDoubles[1, 0]); myStrings[0] = "Joe"; myStrings[1] = "Matt"; myStrings[2] = "Robert"; Console.WriteLine("myStrings[0]: {0}, myStrings[1]: {1}, myStrings[2]: {2}", myStrings[0], myStrings[1], myStrings[2]); }

Binary Opreator

using System; class Binary { public static void Main() { int x, y, result; float floatResult; x = 7; y = 5; result = x + y; Console.WriteLine("x+y: {0}", result); result = x - y; Console.WriteLine("x-y: {0}", result); result = x * y; Console.WriteLine("x*y: {0}", result); result = x / y; Console.WriteLine("x/y: {0}", result); floatResult = (float)x / (float)y; Console.WriteLine("x/y: {0}", floatResult); result = x % y; Console.WriteLine("x%y: {0}", result); result += x; Console.WriteLine("result+=x: {0}", result); }

Boolean opearator

using System; class Booleans { public static void Main() { bool content = true; bool noContent = false; Console.WriteLine("It is {0} that C# Stationprovides C# programming language content.", content); Console.WriteLine("The statement above is not {0}.", noContent); }

Unary opearetors

using System; class Unary { public static void Main() { int unary = 0; int preIncrement; int preDecrement; int postIncrement; int postDecrement; int positive; int negative; sbyte bitNot; bool logNot; preIncrement = ++unary; Console.WriteLine("Pre-Increment: {0}", preIncrement); preDecrement = --unary; Console.WriteLine("Pre-Decrement: {0}", preDecrement); postDecrement = unary--; Console.WriteLine("Post-Decrement: {0}", postDecrement);

postIncrement = unary++; Console.WriteLine("Post-Increment: {0}", postIncrement); Console.WriteLine("Final Value of Unary: {0}", unary); positive = -postIncrement; Console.WriteLine("Positive: {0}", positive); negative = +postIncrement; Console.WriteLine("Negative: {0}", negative); bitNot = 0; bitNot = (sbyte)(~bitNot); Console.WriteLine("Bitwise Not: {0}", bitNot); logNot = false; logNot = !logNot; Console.WriteLine("Logical Not: {0}", logNot); }

IF

using System; class IfSelect { public static void Main() { string myInput; int myInt; Console.Write("Please enter a number: "); myInput = Console.ReadLine(); myInt = Int32.Parse(myInput);// string to int if (myInt > 0) { Console.WriteLine("Your number {0} is greater than zero.",myInt); } if (myInt < 0) Console.WriteLine("Your number is less than zero.",myInt); if (myInt != 0) { Console.WriteLine("Your number {0} is not equal to zero.",myInt); } else { Console.WriteLine("Your number {0} is equal to zero.",myInt); } if (myInt < 0 || myInt == 0) { Console.WriteLine("Your number {0} is less than or equal to zero.",myInt); } else if (myInt > 0 && myInt <= 10) { Console.WriteLine("Your number {0} is between 1 and 10.",myInt); } else if (myInt >10 && myInt <= 20) { Console.WriteLine("Your number {0} is between 11 and 20.",myInt); } else if (myInt > 20 && myInt <= 30) { Console.WriteLine("Your number {0} is between 21 and 30.",myInt); } else { Console.WriteLine("Your number {0} is greater than 30.",myInt); } }

switch

using System; class SwitchSelection { public static void Main() { string myInput; int myInt; begin: Console.Write("Please enter a number between 1 and 3: "); myInput = Console.ReadLine(); myInt = Int32.Parse(myInput); // Switch with integer type switch (myInt) { case 1: Console.WriteLine("Your number is {0}.", myInt); break; case 2: Console.WriteLine("Your number is {0}.", myInt); break; case 3: Console.WriteLine("Your number is {0}.", myInt); break; default: Console.WriteLine("Your number {0} is not between 1 and 3.", myInt); break; }

decide: Console.Write("Type\"continue\"to go on or\"quit\"to stop: "); myInput = Console.ReadLine(); // switch with string type switch (myInput) { case "continue": goto begin; case "quit": Console.WriteLine("bye."); break; defualt: Console.WriteLine("Your input {0} is incorrect.", myInput); goto decide; }

 Loop  Do while  foreach

using System; class ForEachLoop { public static void Main() { string[] names = {"Cheryl","Joe","Matt","Robert"}; foreach (string person in names) { Console.WriteLine("{0}",person); }

using System; class ForLoop { public static void Main() { for (int i=0; i < 20; i++) { if (i == 10) break; if (i % 2 ==0) continue; Console.Write("{0}",i); } Console.WriteLine(); }

using System; class WhileLoop { public static void Main() { int myInt = 0; while (myInt < 10) { Console.Write("{0}",myInt); myInt++; } Console.WriteLine(); }

Methods

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication3 { class myclass { public static int multiply(int x, int y) { int res = x * y; Console.WriteLine("Multiplication = " + res); return res; } public void inc(ref int x) { x = x + 1; } public void equal(int y) { y = y + 1; }

class Program { public int add(int x, int y) { return(x+y); } static void Main(string[] args) { int x = 90; int y = 90; // for static method //Console.WriteLine(" output = " + myclass.multiply(67,9887)); Program p = new Program(); int ans = p.add(56,89); Console.WriteLine("addition ==" + ans); // call by ref Console.WriteLine("X befor fuction call " + x); myc.inc(ref x); Console.WriteLine("X after fuction call " + x); // call by value Console.WriteLine("y befor fuction call " +y); myc.equal(y); Console.WriteLine("y after fuction call " + y); }

Name Sapce

namespace csharp_station.tutorial { class myExample { public static void myPrint() { Console.WriteLine("This is a member of csharp_station.tutorial.myExample."); }

// Namespace Declaration using System; using csTut = csharp_station.tutorial.myExample; // alias // Program start class class AliasDirective { // Main begins program execution public static void Main() { // Call namespace member csTut.myPrint(); myPrint(); } // Potentially ambiguous method static void myPrint() { Console.WriteLine("Not a member of csharp_station.tutorial.myExample."); }

Nested Name space

using System; namespace csharp_station { // nested namespace namespace tutorial { class myExample1 { public static void myPrint1() { Console.WriteLine("First Example of calling another namespace member."); } // program start class class NamespaceCalling { // Main begins program execution public static void Main() { // Write to console tutorial.myExample1.myPrint1(); tutorial.myExample2.myPrint2(); }

namespace csharp_station.tutorial { class myExample2 { public static void myPrint2() { Console.WriteLine("Second Example of calling another namespace member."); }

Class

// Namespace Declaration using System; // helper class class OutputClass { string myString; // Constructor public OutputClass(string inputString) { myString = inputString; } // Instance Method public void printString() { Console.WriteLine("{0}", myString); } // Destructor ~OutputClass() { // Some resource cleanup routines } // Program start class class ExampleClass { // Main begins program execution. public static void Main() { // Instance of OutputClass OutputClass outCl = new OutputClass("This is printed by the output class."); // Call Output class' method outCl.printString(); }

Inheritance

using System; public class ParentClass { public ParentClass() { Console.WriteLine("Parent Constructor."); } public void print() { Console.WriteLine("I'm a Parent Class."); } public class ChildClass : ParentClass { public ChildClass() { Console.WriteLine("Child Constructor."); } public static void Main() { ChildClass child = new ChildClass(); child.print(); }

Derived class talking with base class

using System; public class Parent { string parentString; public Parent() { Console.WriteLine("Parent Constuctor."); } public Parent(string myString) { parentString = myString; Console.WriteLine(parentString); } public void print() { Console.WriteLine("I'm a Parent Class."); } public class Child : Parent { public Child() : base("From Derived") { Console.WriteLine("Child Constuctor."); } public new void print() { base.print(); Console.WriteLine("I'm a Child Class."); } public static void Main() { Child child = new Child(); child.print(); ((Parent)child).print(); } }

Polymorphism

Program.cs using System; public class DrawDemo { public static int Main() { DrawingObject[] dObj = new DrawingObject[4]; dObj[0] = new Line(); dObj[1] = new Circle(); dObj[2] = new Square(); dObj[3] = new DrawingObject(); foreach (DrawingObject drawObj in dObj) { drawObj.Draw(); } return 0; }

using System; public class DrawingObject { public virtual void Draw() { Console.WriteLine("I'm just a generic drawing object."); }

lcs.cs using System; public class Line : DrawingObject { public override void Draw() { Console.WriteLine("I'm a Line."); } public class Circle : DrawingObject { public override void Draw() { Console.WriteLine("I'm a Circle."); } public class Square : DrawingObject { public override void Draw() { Console.WriteLine("I'm a Square."); }

Encapsulation

Traditional way of encapsulation

using System; public class Customer { private int m_id = -1; public int GetID() { return m_id; } public void SetID(int id) { m_id = id; } private string m_name = string.Empty; public string GetName() { return m_name; } public void SetName(string name) { m_name = name; } }

public class CustomerManagerWithAccessorMethods { public static void Main() { Customer cust = new Customer(); cust.SetID(1); cust.SetName("Amelio Rosales"); Console.WriteLine( "ID: {0}, Name: {1}", cust.GetID(), cust.GetName()); Console.ReadKey(); }

 Encapsulating Type State with Properties

public class Customer { private int m_id = -1; public int ID { get { return m_id; } set { m_id = value; } private string m_name = string.Empty; public string Name { get { return m_name; } set { m_name = value; }

using System; public class CustomerManagerWithProperties { public static void Main() { Customer cust = new Customer(); cust.ID = 1; cust.Name = "Amelio Rosales"; Console.WriteLine( "ID: {0}, Name: {1}“, cust.ID, cust.Name); Console.ReadKey(); }

 Read only properties - without set method  Write only properties – without get method

Structure

using System; struct Point { public int x; public int y; public Point(int x, int y) { this.x = x; this.y = y; } public Point Add(Point pt) { Point newPt; newPt.x = x + pt.x; newPt.y = y + pt.y; return newPt; } class StructExample { static void Main(string[] args) { Point pt1 = new Point(1, 1); Point pt2 = new Point(2, 2); Point pt3; pt3 = pt1.Add(pt2); Console.WriteLine("pt3: {0}:{1}",pt3.x,pt3.y); }

Interface

 An interface looks like a class, but has no implementation.  The only thing it contains are declarations of events, indexers, methods and/or properties.  The reason interfaces only provide declarations is because they are inherited by classes and structs, which must provide an implementation for each interface member declared.  So, what are interfaces good for if they don't implement functionality?  They're great for putting together plug-n-play like architectures where components can be interchanged at will.

interface IMyInterface { void MethodToImplement(); }

using System; class InterfaceImplementer : IMyInterface { static void Main() { InterfaceImplementer iImp = new InterfaceImplementer(); iImp.MethodToImplement(); } public void MethodToImplement() { Console.WriteLine("MethodToImplement() called."); }

using System; interface IParentInterface { void ParentInterfaceMethod(); } interface IMyInterface : IParentInterface { void MethodToImplement(); } class InterfaceImplementer : IMyInterface { static void Main() { InterfaceImplementer iImp = new InterfaceImplementer(); iImp.MethodToImplement(); } public void MethodToImplement() { Console.WriteLine("MethodToImplement() called."); } public void ParentInterfaceMethod() { Console.WriteLine("ParentInterfaceMethod() called."); }

Indexers

 Indexer are location indicators and used to access class objects, just like accessing elements in an array.  Indexers look like a properties with two differences.  Indexer takes index argument and look like an array  Indexer is declared using the name this

Class list { ArrayList array = new ArrayList(); Public object this [int index] { get { if(index = array.count) { return null; } else { return (array [index]); } set { array[index]=value; }

class IndexserTest { Public static void Main() { List l = new List(); l [0] = “123”; l[1] = “abc”; l[2]=“xyz”; for(int i=0; I < list.count;i++) Console.WriteLine(list[i]); }

Properties are static indexer is instance member get set

ARRAYARRAYLIST 1. Char[] vowel=new Char[]; ArrayList a_list=new ArrayList(); 2. Array is in the System namespace ArrayList is in the System.Collections namespace. 3. The capacity of an Array is fixed ArrayList can increase and decrease size dynamically 4. An Array is a collection of similar items ArrayList can hold item of different types 5. An Array can have multiple dimensions ArrayList always has exactly one dimension

Delegates

 A delegate is a C# language element that allows you to reference a method. If you were a C or C++ programmer, this would sound familiar because a delegate is basically a function pointer.  Why to use ? -- Gives you maximum flexibility to implement any functionality you want at runtime.  which provide dynamic run-time method invocation services.

class Program { public delegate int SumPtr(int x, int y);//declaration public int add(int x, int y) { return(x+y); } static void Main(string[] args) { int x = 90; int y = 90; Program p = new Program(); int ans = p.add(56,89); // with delegates SumPtr sPtr = new SumPtr(p.add); //instantiation Console.WriteLine(" with deleget"+ sPtr(34, 6));//invocation } } }

 Sometimes, however, we don't want to call a function directly – we'd like to be able to pass it to somebody else so that they can call it.  This is especially useful in an event-driven system such as a graphical user interface, when I want some code to be executed when the user clicks on a button, or when I want to log some information but can't specify how it is logged

 Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object.  The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

 In C#, delegates are multicast, which means that they can point to more than one function at a time  Delegates can be added and subtracted

delegate void MyDelegate(string s); class MyClass { public static void Hello(string s) { Console.WriteLine(" Hello, {0}!", s); } public static void Goodbye(string s) { Console.WriteLine(" Goodbye, {0}!", s); }

public static void Main() { MyDelegate a, b, c, d; a = new MyDelegate(Hello); b = new MyDelegate(Goodbye); c = a + b; d = c - a; Console.WriteLine("Invoking delegate a:"); a("A"); Console.WriteLine("Invoking delegate b:"); b("B"); Console.WriteLine("Invoking delegate c:"); c("C"); Console.WriteLine("Invoking delegate d:"); d("D"); }

 Event

 The Event model in C# finds its roots in the event programming model that is popular in asynchronous programming.  The basic foundation behind this programming model is the idea of "publisher and subscribers."

 We want to cause some code to be executed when something happens elsewhere in the system - or "handle the event".  To do this, we create specific methods for the code we want to be executed.  The glue between the event and the methods to be executed are the delegates

 Events and delegates work hand-in-hand.  Any class, including the same class that the event is declared in, may register one of its methods for the event.  This occurs through a delegate, which specifies the signature of the method that is registered for the event.  The delegate may be one of the pre-defined.NET delegates or one you declare yourself. Whichever is appropriate, you assign the delegate to the event, which effectively registers the method that will be called when the event fires.  Event.cs Event.cs

File Handling

 Byte oriented file require FileSteram object defined in system.IO.  Using system.io

 To create byte stream linked to a file create File stream object.  Constructor  FileStream (string path. FileMode mode)  FileStream (string path. FileMode mode, FileAccess access)  Exceptions FileNotFoundException, IOException,ArgumentNullException,ArgumentException,SecurityException,PathTooLongException  Close void close(); FileMode.Append FIleMode.Create FileMode.CreateNew FileMode.Open FileMode.OpenOrCrea te FileMode.Truncate FileAccess.Rea d FileAccess.Wri te FileAccess.ReadWrite

 int ReadByte() – each time reads single byte from file,returns -1 when EOF  int Read(byte[] array, int offset, int count)  Attempts to read up to count byte into array starting at array[offset], returns number of bytes successfully read

 Void WriteByte(byte value)  Void Writebyte[] array, int offset, int count)  Void Flush()

Operates directly on Unicode characters. At the OS level file contain set of bytes using stream reader and stream writer does not alter this fact

 Constructor 1 - StreamWrite (string path)  Constructor 2 - SteramWriter (string path, bool append)  StreamWriter automatically handles conversion of character to byte.

FileStream fout; try { fout = new FileStream(“test.txt”,FilleMode.Create); } catch() StreamWriter fstr_out = new StreamWriter(fout); try { str = Console.ReadLine(); fstr_out.Write(str); }catch()

StreamWriter fstr_out = null; fstr_out = new StreamWriter(“test.txt”); try { str = Console.ReadLine(); fstr_out.Write(str); }catch()

FileStream fin; try { fin = new FileStream(“test.txt”,FilleMode.Open); } catch() StreamReader fstr_in = new StreamReader(fin); try { While((s= fstr_in.ReadLine() )!= NULL ) Console.WriteLine(s); }catch()

 filehandling.cs filehandling.cs

 Seek() defined by FileStream.  long Seek(long offset,SeekOrigin origin)  Offset – new position in a byte  Origin – file pointer from location  SeekOrigin.Begin  SeekOrigin.Current  SeekOrigin.End

try { F = new FileStream(“ran.txt”,FileMode.Create) for(int i=0;i<26;i++) F.WriteByte((byte)’(A’ + i)) F.Seek(0,SeekOrigin.Begin); Ch = (char) F.ReadByte(); Console.WriteLine(ch); } catch(IOEXCeption exe) { Console.WriteLine(exe.Message) }

Generics

 Collection Classes have the following properties Collection classes are defined as part of the System.Collections or System.Collections.Generic namespace.  Most collection classes derive from the interfaces ICollection, IComparer, IEnumerable, IList, IDictionary, and IDictionaryEnumerator and their generic equivalents.  Using generic collection classes provides increased type-safety and in some cases can provide better performance, especially when storing value types. For more information, see Benefits of Generics.

ARRAYARRAYLIST 1. Char[] vowel=new Char[]; ArrayList a_list=new ArrayList(); 2. Array is in the System namespace ArrayList is in the System.Collections namespace. 3. The capacity of an Array is fixed ArrayList can increase and decrease size dynamically 4. An Array is a collection of similar items ArrayList can hold item of different types 5. An Array can have multiple dimensions ArrayList always has exactly one dimension

 The problem with ArrayList and all the other.NET v1.0 collections is that they operate on type object.  Since all objects derive from the object type, you can assign anything to an ArrayList.  The problem with this is that you incur performance overhead converting value type objects to and from the object type and a single ArrayList could accidentally hold different types, which would cause hard to find errors at runtime because you wrote code to work with one type.  Generic collections fix these problems.

 A generic collection is strongly typed (type safe), meaning that you can only put one type of object into it.  This eliminates type mismatches at runtime.  Another benefit of type safety is that performance is better with value type objects because they don't incur overhead of being converted to and from type object.  With generic collections, you have the best of all worlds because they are strongly typed, like arrays, and you have the additional functionality, like ArrayList and other non-generic collections, without the problems.

 List  Dictionary

 The pattern for using a generic List collection is similar to arrays. You declare the List, populate its members, then access the members.  List, which is referred to as List of int  List or List  Using the Add method, you can add as many int objects to the collection as you want.  List class has many more methods you can use, such as Contains, Remove, and more.

List myInts = new List (); myInts.Add(1); myInts.Add(2); myInts.Add(3); for (int i = 0; i < myInts.Count; i++) { Console.WriteLine("MyInts: {0}", myInts[i]); }

 Example of Dictionary

 Another very useful generic collection is the Dictionary, which works with key/value pairs.  There is a non-generic collection, called a Hashtable that does the same thing, except that it operates on type object.  Example is that you have a list of Customers that you need to work with. It would be natural to keep track of these Customers via their CustomerID

public class Customer { public Customer(int id, string name) { ID = id; Name = name; } private int m_id; public int ID { get { return m_id; } set { m_id = value; } } private string m_name; public string Name { get { return m_name; } set { m_name = value; } }

Dictionary customers = new Dictionary (); Customer cust1 = new Customer(1, "Cust 1"); Customer cust2 = new Customer(2, "Cust 2"); Customer cust3 = new Customer(3, "Cust 3"); customers.Add(cust1.ID, cust1); customers.Add(cust2.ID, cust2); customers.Add(cust3.ID, cust3); foreach (KeyValuePair custKeyVal in customers) { Console.WriteLine( "Customer ID: {0}, Name: {1}", custKeyVal.Key, custKeyVal.Value.Name); }

 The customers variable is declared as a Dictionary.  Considering that the formal declaration of Dictionary is Dictionary, the meaning of customers is that it is a Dictionary where the key is type int and the value is type Customer.  Therefore, any time you add an entry to the Dictionary, you must provide the key because it is also the key that you will use to extract a specified Customer from the Dictionary.

 Implementation of Ls/Dir command

using System;using System.IO; class Program { static void Main() { // Put all file names in root directory into array. string[] array1 = // Put all txt files in root directory into array. string[] array2 = "*.BIN"); // <-- Case-insensitive // Display all files. Console.WriteLine("--- Files: ---"); foreach (string name in array1) { Console.WriteLine(name); } // Display all BIN files. Console.WriteLine("--- BIN Files: ---"); foreach (string name in array2) { Console.WriteLine(name); } }}

using System; using System.IO; public class Temp { public static void Main(string[] args) { DirectoryInfo di = new DirectoryInfo("."); foreach(FileInfo fi in di.GetFiles("*.cs")) { Console.WriteLine("Looking at file \""+fi.FullName+"\""); }

using System;using System.Threading; public class RegistrarProxy { private static Timer _timer; private static readonly TimerCallback _timerCallback = timerDelegate; public void Init() { _timer = new Timer(_timerCallback, null, 0, 2000); //repeat every 2000 milliseconds } private static void timerDelegate(object state) { Console.WriteLine("timerDeletegate: " + DateTime.Now); } public static void Main() { RegistrarProxy rp = new RegistrarProxy(); rp.Init(); Console.In.Read(); //let's wait until the "return" key pressed }}

 Write C# program to display emp table content in tabular format  Write a c# program to list the directory in a drive selected by user  File copy – ask user how many lines to copy from source to destination  Write a program for all string oprations (menu driven)