Mycsppt

48
the painful aspects of the C language manual memory management ugly pointer arithmetic and ugly syntactical constructs c++ is a difficult and error-prone experience using Java typically means “ Java front-to- back” Java offers little hope of language integration limited ability to Evil disadvantages ! C++ Java

description

C sharp beginner PPT

Transcript of Mycsppt

Page 1: Mycsppt

the painful aspects of the C language manual memory managementugly pointer arithmeticand ugly syntactical constructsc++ is a difficult and error-prone experience

using Java typically means “ Java front-to-back” Java offers little hope of language integrationlimited ability to access non-Java APIs

Evil disadvantages !C++

Java

Page 2: Mycsppt

Simplified syntax

Cross-language capabilities

Header files have also been removed from C#. The namespace and reference operators, :: and -> respectively, have been replaced with a single operator, the period (.).

Automatic garbage collection and exception handling

Pointers no longer needed (but optional) with The power to be unsafe

Definition of classes and functions can be done in any order

Declaration of functions and classes not needed

Classes can be defined within classes

There are no global functions or variables, everything belongs to a class

All the variables are initialized to their default values before being used(automatic)

You can't use non-boolean variables (integers, floats...) as conditions

Why C#

Page 3: Mycsppt
Page 4: Mycsppt

What is the .NET Framework?

The .NET Framework a code-execution environment that promotes:

• Safe execution of code

• Memory management

• Code-access security

• Common Type System (CTS)

• Managed/Unmanaged code

• Services, Layout and more …

Page 5: Mycsppt

The IDE …

• IDE:IntegratedDevelopmentEnvironment

Microsoft Visual Studio .NET 2008Microsoft Visual C# 2008 Express Edition

Page 6: Mycsppt
Page 7: Mycsppt
Page 8: Mycsppt
Page 9: Mycsppt

An int has methods associated with it. For example, you can use the ToString method to get a string value for an int, as shown below.

int Counter=14;Console.Write(Counter.ToString());

In addition,a new type OBJECT is added , even literal strings can

be treated as objects and support a variety of methods, such as Trim, ToUpper, ToLower, and many others, as shown here:

Console.Write("hello, world".ToUpper());

Oop data type !

Page 10: Mycsppt

input output

Page 11: Mycsppt

ReadlineConsole.ReadLine allows you to read a string of characters, which you can test and transform with other methods to accomplish a task

using System; class Program { static void Main() { while (true) // Loop indefinitely { Console.WriteLine("Enter input:"); string line = Console.ReadLine(); if (line == "exit") break; Console.Write("You typed "); Console.Write(line.Length); Console.WriteLine(" character(s)"); } }}

--- Output of the program --- Enter input: aya You typed 3 character(s) Enter input: salsabeelYou typed 9 acharacter(s) Enter input:

Page 12: Mycsppt

ReadlineReading integer from consoleusing System; class Program { static void Main() {Console.WriteLine("Type an integer:");string line = Console.ReadLine(); int value;if (int.TryParse(line, out value)) { Console.Write("Multiply integer by 10: "); Console.WriteLine(value * 10); } else { Console.WriteLine("Not an integer!"); } } }

--- Output of the program --- Type an integer: 4356 Multiply integer by 10: 43560

Page 13: Mycsppt

Writelinethere are 19 overloads on Console.WriteLine, and 18 on Write. the overloads for WriteLine accept an int, a string, and a bool.

using System; class Program { static void Main() { int valueInt = 4; Console.WriteLine(value); string valueString = "Your string"; Console.WriteLine(valueString);bool valueBool = false; Console.WriteLine(valueBool); } }

Page 14: Mycsppt

WritelineWriting arrays of characters

using System; class Program { static void Main() { char[] array = new char[] { 'a', 'b', 'c', 'd' }; Console.WriteLine(array); Console.WriteLine(array, 1, 2); } }

Page 15: Mycsppt

Writelineformatting

using System; class Program { static void Main() { string value1 = “aya"; string value2 = “amira“; string value3 = “afnan"; Console.WriteLine("{0}, {1}, {2}", value1, value2, value3); } }

Page 16: Mycsppt

C#1 st program// Namespace Declarationusing System;

// Program start classclass Welcome{ // Main begins program execution. static void Main() { // Write to console Console.WriteLine(“Hello World!"); }}

Page 17: Mycsppt

Operators

Page 18: Mycsppt

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int l1; int L2; int area; L1 = 20; L2= 10; area = L1 * L2; // Calculate the area of rectangle Console.WriteLine("Area of Rectangle is : {0}“,area); Console.ReadLine(); } } }

C#2 nd program

Page 19: Mycsppt

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { int x, y, result; float floatresult=0f; 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); Console.ReadLine(); }}}

C#3 rd program

Page 20: Mycsppt

1. for loop2. for each/in loop3. while loop4. do/while loop

LOOPS

Page 21: Mycsppt

• for loopfor(int i = 0; i < 4; i++)

{ Console.WriteLine("Number is: {0} ", i); }

• for each/in loop

static void Main(){

string[] carTypes = {"Ford", "BMW", “Matria", “Mini Coper" };

foreach (string c in carTypes) Console.WriteLine(c);int[] myInts = { 10, 20, 30, 40 };foreach (int i in myInts) Console.WriteLine(i);

}

Page 22: Mycsppt

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int x = 1; int area; while (x <= 5) { area = x * x; Console.WriteLine("Area with side = {0} is {1}", x , area); x = x + 1; } Console.ReadLine(); } } }

• while loop

Page 23: Mycsppt

Jump Statements

Page 24: Mycsppt

for (int i= 1; i<= 4;i++) {if (i < 2) {continue;}Console.WriteLine (i);}

int i = 0;while (i < 4){Console.WriteLine(i.ToString());if (i == 2)break;i++;}

breakContinue

int i = 0;while (i < 3){Console.WriteLine (i.ToString());if (i == 2)goto Complete;i++;}

Goto

Page 25: Mycsppt

Decisions

Page 26: Mycsppt

int number; Console.WriteLine("Please enter a number between 0 &10:"); number = int.Parse(Console.ReadLine()); if(number > 10) Console.WriteLine("Hey! The number should be 10 or less!");

else if(number < 0) Console.WriteLine("Hey! The number should be 0 or more!"); else Console.WriteLine("Good job!"); Console.ReadLine();

If statement

Page 27: Mycsppt

int Counter=14;if (Counter=14) { //do something }

Attempting to compile this code will return an error stating:Cannot implicitly convert type ‘int’ to ‘bool’

How nice !

Page 28: Mycsppt

Switch (country) {case"Germany": statues = “in love“;case“Las vigas":statues = “player";break;case"England": statues=“single “;case“spain":statues =“in a relationship but I think he is cheating on me“;break;casenull :Console.WriteLine("no country specified");break;default:Console.WriteLine("don't know staues of {0}", Country);break;}

Switch statment

Page 29: Mycsppt

o

Classes vs. Objects

En- capsulation

o

Static Data /Methods

Access Visibilitypublic, private,

protected

pInheritance

The is-a relation …

InterfaceThe has-a relation

Polymorphism

abstractionsealed classes

Page 30: Mycsppt

Inheritance

I make the code more modular by dividing larger pieces of code into smaller, more maintainable ones.

I introduce a hierarchy where objects become more specialized as you move down the tree

I can now reuse code.

The is-a relation

Page 31: Mycsppt
Page 32: Mycsppt
Page 33: Mycsppt

Inheritance in code class Character{public void Walk(){Console.WriteLine("Character walking!");} public void Talk(){Console.WriteLine("Character is talking about something");} public void Say(string thingToSay){Console.WriteLine("Character says: {0}", thingToSay);} } class Program{static void Main(string[] args){Character Afnan = new Character();Afnan.Say("Hello World!");}}

Page 34: Mycsppt

Inheritance in code class Alien : Character{public void ChangeLocation(string currentLocation, string newLocation){Console.WriteLine("The alien teleported from {0} to {1}",currentLocation, newLocation);} public void Hide(){Console.WriteLine("The alien is hiding.");}}}

Page 35: Mycsppt

Inheritance in code class Program{static void Main(string[] args){Alien Afnan = new Character();Afnan.Say("Hello World!");Afnan.hide();

}}

Page 36: Mycsppt

polymorphism?What is arguably more powerful, however, is the second aspect of inheritance: polymorphism.

Poly means many and morph means form. Thus, polymorphism refers to being able to use many forms of a type.

Do u remember function overloading in C++?

Page 37: Mycsppt

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

using System;

public class Line : DrawingObject{ public override void Draw() { Console.WriteLine("I'm a Line."); }

public class Square : DrawingObject{ public override void Draw() { Console.WriteLine("I'm a Square."); }}

using System;public class DrawDemo{ public static int Main( ) { DrawingObject[]Aya= new DrawingObject[4];

Aya[0] = new Line(); Aya[1] = new Circle(); Aya[2] = new Square(); Aya[3] = new DrawingObject();

foreach (DrawingObject Obj in Aya) Obj.Draw(); return 0; }}

public class Circle : DrawingObject{ public override void Draw() { Console.WriteLine("I'm a Circle."); }}

Page 38: Mycsppt

Access Visibility ?Public:

The type or member may be accessed by any code, internal or external

Private: This applies to members (and nested types, a form of member) only. It means that the member may only be accessed by code inside the type on which the member is defined.

Family (Protected): Applies only to members, and means a member may be

accessed only by the type on which the member is defined and any subclasses (and their subclasses, and so on)

Page 39: Mycsppt

Why static methods ?Static methods enable you to call code without an instance of the class in which it's defined. A static method should be self-contained. This is to say that it willperform its function without requiring or saving any data.

public static double Multiply(double a, double b){return a*b;}

Page 40: Mycsppt

Exception handeling Bugs : These are errors on the part of the programmer. For example, If you fail to delete dynamically allocated memory (resulting in a memory leak).

User/programmer/made by programmer errors: For example, an end user who enters a malformed string into a text box could very well generate an error .

Exceptions: are typically regarded as runtime anomalies that are difficult, if not impossible, to account for while programming your application.

Possible exceptions include attempting to connect to a database that no longer exists, opening a corrupted file, or contacting a machine that is currently offline. In each of these cases, the programmer (and end user) has little control over these “exceptional” circumstances.

Page 41: Mycsppt

class Car{// Constant for maximum speed.public const int MaxSpeed = 100;// Internal state data.private int currSpeed;private string petName;// Is the car still operational?private bool carIsDead;// A car has-a radio.private Radio theMusicBox = new Radio();// Constructors.public Car() {}public Car(string name, int currSp){currSpeed = currSp;petName = name;}public void CrankTunes(bool state){// Delegate request to inner object.theMusicBox.TurnOn(state);}

// See if Car has overheated.public void Accelerate(int delta){if (carIsDead)Console.WriteLine("{0} is out of order...", petName);else{currSpeed += delta;if (currSpeed > MaxSpeed){Console.WriteLine("{0} has overheated!", petName);currSpeed = 0;carIsDead = true;}elseConsole.WriteLine("=> CurrSpeed = {0}", currSpeed);}}}

Page 42: Mycsppt

static void Main(string[] args){Console.WriteLine("***** Simple Exception Example *****");Console.WriteLine("=> Creating a car and stepping on it!");Car myCar = new Car(“MyCar", 20);myCar.CrankTunes(true);

try{for(int i = 0; i < 10; i++)myCar. Accelerate(10);}

catch(Exception e){Console.WriteLine("\n*** Error! ***");Console.WriteLine("Method: {0}", e.TargetSite);Console.WriteLine("Message: {0}", e.Message);Console.WriteLine("Source: {0}", e.Source);}// The error has been handled, processing continues with the next statement.Console.WriteLine("\n***** Out of exception logic *****");Console.ReadLine();}

Page 43: Mycsppt
Page 44: Mycsppt

File organization

Page 45: Mycsppt

Value Description

FileMode.Append append to the end of file.or create then append

FileMode.Createcreate a new output file. Any preexisting file by the same name will be destroyed. overwrites

FileMode.CreateNew create a new output file. The file must not already exist. otherwise opens

FileMode.Open open a preexisting file. Otherwise exception

FileMode.OpenOrCreate open a file if it exists, or create the file if it does not already exist.

FileMode.Truncate open a preexisting file, but reduce its length to zero.

FILE MODES

FILE ACCESSRead write readwrite

Page 46: Mycsppt

TXT FILE ORGANIZATIONDatabase=#of Files = #of records =#of fields=#of charactersData structures help getting data in minimum seeking times

Field structure

Fixed length delimiter Length

indicatorKeyword=value

Page 47: Mycsppt

using System.IO;

FileStream file = new FileStream("path.txt", FileMode, FileAccess);

StreamWriter sw = new StreamWriter(file);

To write to a file we will need to use class StreamWriter, which is derived from the TextWriter class.

sw.Write("Hello file system world!");

Here is a simple example:

sw.Close();

Writing to a file:

Page 48: Mycsppt

Reading from a file:

string s = sr.ReadToEnd();

StreamReader sr = new StreamReader(file);

sr.Close();

file.Close();

Read, ReadBlock, ReadLine, or ReadToEnd