Published on

C sharp beginner PPT

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. the painful aspects of the C languagemanual memory managementugly pointer arithmeticand ugly syntactical constructsc++ is a difficult and error-prone experienceusing Java typically means “ Javafront-to-back” Java offers littlehope of language integrationlimited ability to access non-JavaAPIs
  2. 2. Simplified syntaxCross-language capabilitiesPointers no longer needed (but optional) with The power to be unsafeYou cant use non-boolean variables (integers, floats...) as conditionsThere are no global functions or variables, everything belongs to a classAll the variables are initialized to their default values before being used(automatic)Classes can be defined within classesDeclaration of functions and classes not neededDefinition of classes and functions can be done in any orderAutomatic garbage collection and exception handlingHeader files have also been removed from C#. The namespace and reference operators, ::and -> respectively, have been replaced with a single operator, the period (.).
  3. 3. 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 …
  4. 4. The IDE …• IDE: Integrated Development Environment Microsoft Visual Studio .NET 2008 Microsoft Visual C# 2008 Express Edition
  5. 5. An int has methods associated with it.For example, you can use the ToString method to get a stringvalue for an int, as shown Counter=14;Console.Write(Counter.ToString());In addition,a new type OBJECT is added , even literal strings canbe treated as objects and support a variety of methods, suchas Trim, ToUpper, ToLower, and many others, as shown here:Console.Write("hello, world".ToUpper());
  6. 6. Console.ReadLineallows you to read a string of characters, which you can test andtransform with other methods to accomplish a taskusing System;class Program --- Output of the program ---{ static void Main() Enter input: aya { You typed 3 character(s)while (true) // Loop indefinitely Enter input: salsabeel{Console.WriteLine("Enter input:"); You typed 9 acharacter(s)string line = Console.ReadLine(); Enter input: if (line == "exit") break;Console.Write("You typed ");Console.Write(line.Length); Console.WriteLine("character(s)");} }}
  7. 7. Reading integer from consoleusing System; class Program { --- Output of the program --- static void Main() { Type an integer: 4356 MultiplyConsole.WriteLine("Type an integer:"); integer by 10: 43560string 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!"); } }}
  8. 8. there 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); } }
  9. 9. Writing arrays of charactersusing System;class Program {static void Main(){char[] array = new char[] { a, b, c, d };Console.WriteLine(array); Console.WriteLine(array, 1, 2); } }
  10. 10. formattingusing System; class Program {static void Main() { string value1 = “aya";string value2 = “amira“; string value3 = “afnan"; Console.WriteLine("{0}, {1}, {2}", value1, value2,value3); } }
  11. 11. // Namespace Declarationusing System;// Program start classclass Welcome{ // Main begins program execution. static void Main() { // Write to console Console.WriteLine(“Hello World!"); }}
  12. 12. 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 rectangleConsole.WriteLine("Area of Rectangle is : {0}“,area);Console.ReadLine();}}}
  13. 13. 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(); }}}
  14. 14. 1. for loop2. for each/in loop3. while loop4. do/while loop
  15. 15. • for loop for(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); }
  16. 16. • while loopusing 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(); }}}
  17. 17. int i = 0;for (int i= 1; i<= 4;i++) while (i < 4){ {if (i < 2) Console.WriteLine(i.ToString());{ if (i == 2)continue; break;} i++;Console.WriteLine (i); }}int i = 0;while (i < 3){Console.WriteLine (i.ToString());if (i == 2)goto Complete;i++;}
  18. 18. 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();
  19. 19. int Counter=14;if (Counter=14) { //do something }Attempting to compile this code will return an errorstating:Cannot implicitly convert type ‘int’ to ‘bool’
  20. 20. 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("dont know staues of {0}", Country);break;}
  21. 21. Inheritance The is-a relation …Classes vs. Static Data Objects /Methods Interface The has-a relation Access VisibilityEn- capsulation public, private, protected Polymorphism abstraction sealed classes
  22. 22. The is-a relationI make the code more modular by dividing larger pieces of code intosmaller, more maintainable ones.I introduce a hierarchy where objects become more specialized asyou move down the treeI can now reuse code.
  23. 23. 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!");}}
  24. 24. class Alien : Character{public void ChangeLocation(string currentLocation, stringnewLocation){Console.WriteLine("The alien teleported from {0} to{1}",currentLocation, newLocation);}public void Hide(){Console.WriteLine("The alien is hiding.");}}}
  25. 25. class Program{static void Main(string[] args){Alien Afnan = new Character();Afnan.Say("Hello World!");Afnan.hide();}}
  26. 26. What is arguably more powerful, however, is thesecond aspect of inheritance: polymorphism.Poly means many and morph means form. Thus, polymorphism refers to being able to use manyforms of a type.Do u remember function overloading in C++?
  27. 27. using System; public class Square : DrawingObjectpublic class DrawingObject {{ public override void Draw() public virtual void Draw() { { Console.WriteLine("Im a Square."); Console.WriteLine("Im just a drawing }}object."); using System; } public class DrawDemo} { public static int Main( )using System; { DrawingObject[]Aya= new DrawingObject[4];public class Line : DrawingObject{ Aya[0] = new Line(); public override void Draw() Aya[1] = new Circle(); { Aya[2] = new Square(); Console.WriteLine("Im a Line."); Aya[3] = new DrawingObject(); }public class Circle : DrawingObject{ foreach (DrawingObject Obj in Aya) public override void Draw() Obj.Draw(); { return 0; Console.WriteLine("Im a Circle."); } } }}
  28. 28. Public: The type or member may be accessed by any code, internal or externalPrivate: 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)
  29. 29. Static methods enable you to call code without an instance of theclass in which its 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;}
  30. 30. Bugs : These are errors on the part of the programmer. For example, If you failto 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 boxcould very well generate an error .Exceptions:are typically regarded as runtime anomalies that are difficult, if notimpossible, to account for while programming your application. Possible exceptions include attempting to connect to a database that nolonger exists, opening a corrupted file, or contacting a machine that iscurrently offline. In each of these cases, the programmer (and end user)has little control over these “exceptional” circumstances.
  31. 31. class Car // See if Car has overheated.{ public void Accelerate(int delta)// Constant for maximum speed. {public const int MaxSpeed = 100; if (carIsDead)// Internal state data. Console.WriteLine("{0} is out of order...",private int currSpeed; petName);private string petName; else// Is the car still operational? {private bool carIsDead; currSpeed += delta;// A car has-a radio. if (currSpeed > MaxSpeed)private Radio theMusicBox = new Radio(); {// Constructors. Console.WriteLine("{0} has overheated!",public Car() {} petName);public Car(string name, int currSp) currSpeed = 0;{ carIsDead = true;currSpeed = currSp; }petName = name; else} Console.WriteLine("=> CurrSpeed = {0}",public void CrankTunes(bool state) currSpeed);{ }// Delegate request to inner object. }theMusicBox.TurnOn(state); }}
  32. 32. 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);tryfor(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();}
  33. 33. Value Description append to the end of file.or create thenFileMode.Append append create a new output file. Any preexisting fileFileMode.Create by the same name will be destroyed. overwrites create a new output file. The file must notFileMode.CreateNew already exist. otherwise opensFileMode.Open open a preexisting file. Otherwise exception open a file if it exists, or create the file if itFileMode.OpenOrCreate does not already exist. open a preexisting file, but reduce its lengthFileMode.Truncate to zero. Read write readwrite
  34. 34. Database=#of Files = #of records =#of fields=#of charactersData structures help getting data in minimum seeking times Field structure Fixed Length Keyword delimiter length indicator =value
  35. 35. Writing to a file: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 derivedfrom the TextWriter class.Here is a simpleexample: sw.Write("Hello file system world!"); sw.Close();
  36. 36. Reading from a file: Read, ReadBlock, ReadLine, or ReadToEndStreamReader sr = new StreamReader(file);string s = sr.ReadToEnd();sr.Close();file.Close();