Introduction to C

Introduction to C PowerPoint PPT Presentation


  • 49 Views
  • Uploaded on
  • Presentation posted in: General

Ancestors of C

Download Presentation

Introduction to C

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


1. Introduction to C# C# is a Microsoft product It is meant to support their .NET technology Web-enabled solutions High versatility Networked web-based solutions

2. Ancestors of C# Algol 60 C C++ Visual Basic (VB) These are the languages from which C# was built upon, taking features and designs from each Algol 60 – regular syntax, modular structure, high level language C – support machine oriented solutions and problem solving methods a single developer, Denise Ritchie, gave it cohesion C++ - Object oriented programming (OOP) – supported event driven activities Visual Basic- graphical user interface (GUI) + graphical development interface (drag and drop) sophisticated screen development These are the languages from which C# was built upon, taking features and designs from each Algol 60 – regular syntax, modular structure, high level language C – support machine oriented solutions and problem solving methods a single developer, Denise Ritchie, gave it cohesion C++ - Object oriented programming (OOP) – supported event driven activities Visual Basic- graphical user interface (GUI) + graphical development interface (drag and drop) sophisticated screen development

3. .Net language features OOP Security model Type systems Support for all .NET based classes Support for most .NET framework classes Development / Debugging tools Intermediate language code to native languages translators C# produces Microsoft intermediate language code (MSIL) from its compiler. This MSIL is converted to native code by the machine on which it is executed, thereby providing universality. C# produces Microsoft intermediate language code (MSIL) from its compiler. This MSIL is converted to native code by the machine on which it is executed, thereby providing universality.

4. Current Status Microsoft has submitted C# for standardization Microsoft has made it clear that C# will be its “tool of choice” for its future network strategy

5. Variables Local variables Declared inside a method Fields Declared in a struct or class

6. Definite assignment proven by the compiler to have been automatically initialized the target of at least one assignment An initially assigned variable is always considered definitely assigned: static variables, instance variables of class instances, array elements, values parameters, reference parameters, instance variables of initially assigned struct variables, and variables declared in a catch clause or in a foreach statement

7. For initially unassigned variables to become definitely assigned: all execution paths leading to that location contain an assignment statement where the variable is: the left operand an invocation expression or object creation expression that passes the variable as an output parameter a local variable declaration that includes a variable initializer

8. Examples instance variables of initially unassigned struct variables output parameters local variables with the exception of those declared in a catch clause or a foreach statement

9. Variable Attributes Name (statically bound) Type (statically bound) Scope Lifetime Value

10. Binding Times Attritubutes bound at compile time: name, type Attributes bound at run time: scope, lifetime, value

11. Type Inference Done at compile time Done when a generic function is called static void Swap<T>(ref T lhs, ref T rhs) { T temp; temp = lhs; lhs = rhs; rhs = temp; }

12. · Call to Swap() with an int type argument: public static void TestSwap() { int a = 1; int b = 2; Swap<int>(ref a, ref b); System.Console.WriteLine(a + " " + b); }

13. Call to Swap() without type argument: Swap(ref a, ref b); The compiler infers the type by static and instance methods Type inference does not work with methods with no parameters

14. Static Variables Do not exist in C# Unnecessary when you can define member fields instead Whenever a variable is declared, it is bound to an instance of a class Gets its own copies of the fields in the class

15. Example CreditCardAccountPremium cp1 = new CreditCardAccountPremium(); CreditCardAccountPremium cp2 = new CreditCardAccountPremium(); cp1.setFirstName("George"); cp2.setFirstName("Harry"); • cp1 and cp2 each contain their own string, so changing FirstName in cp2 doesn’t affect FirstName in cp1

16. Data Types Value type Allocated on the stack Contains data When copied, independent copies of the data are made structs Reference type Allocated on the heap Contains address of a memory location When copied, a reference is copied, making both variables point to the same address Classes and interfaces

17. Primitive Value Data Types Sbyte: 8-bit unsigned integer Byte: 8-bit signed integer Char: 16-bit character Float: 32-bit floating point Double: 64-bit floating point Decimal: 28 significant digits Ushort: 16-bit unsigned integer Short: 16-bit signed integer Uint: 32-bit unsigned integer Int: 32-bit signed integer Ulong: 64-bit unsigned integer Long: 64-bit signed integer Bool: holds true or false

18. Primitive Reference Data Types string Object

19. Once again, structs are value types, classes are reference types Fun f1 = new Fun(); // Fun is a struct Boredom b1 = new Boredom(); // Boredom is a class one memory space will be allocated for f1 2 spaces will be allocated: one for a new Boredom object and one for its reference (b1.) Boredom b1; // Allocate the reference b1 = new Boredom(); // Allocate the object

20. Copying these objects to new variables: Fun f2 = f1; Boredom b2 = b1; • f2, being a struct object, becomes a copy independent of f1 with it’s own separate fields. • When b2 was copied, we copied a reference, so b1 and b2 point to the same object • of particular interest when passing parameters. (In C#, parameters are by default passed by value.)

21. Fun moreFun = new Fun (0, 0); // a new value-type variable Boredom lessBoredom = new Boredom(); // a new reference-type variable void Test (Fun f, Boredom b) { f.X = 100; // No effect on moreFun since p is a copy b.Text = “Hello, World!”; // This will change lessBoredom’s caption // since lessBoredom and b point to the //same object b = null; // No effect on lessBoredom } • Assigning null to b has no effect because f is a copy of a reference – and we’ve only erased the copy.

22. String Manipulation Concatenation with “+” operator Testing for equality “==“ operator Compare method

23. Compare Method Returns an integer value of how the two strings differ If return value = 0, the strings are equal If return value < 0, the first operand is alphabetically less than the second If return value > 0, the first operand is alphabetically greater than the second Evaluated from left to right by their equivalent ASCII value

24. Example string string1 = ""; string string2 = ""; Console.Write( "Enter string 1: " ); string1 = Console.ReadLine(); Console.Write( "Enter string 2: " ); string2 = Console.ReadLine(); int compare = String.Compare( string1, string2 ); if( compare == 0 ) { Console.WriteLine( "The strings {0} and {1} are the same.\n", str1, str2 ); }

25. Example Continued else if( compare < 0 ) { Console.WriteLine( "The string {0} is less than {1}", str1, str2 ); } else if( compare > 0 ){ Console.WriteLine( "The string {0} is greater than {1}", str1, str2 ); }

26. Enumeration Types Underlying type options: byte, sbyte, short, ushort, int, uint, long or ulong Must be able to represent all values defined in enumeration Default underlying type: int

27. Enumeration Declaration enum Color: long { Red, Green = 10, Blue }

28. class Test{ static void Main(){ Console.WriteLine(StringFromColor(Color.Red)); Console.WriteLine(StringFromColor(Color.Green)); Console.WriteLine(StringFromColor(Color.Blue)); } static string StringFromColor(Color c){ switch (c) { case Color.Red: return String.Format("Red = {0}", (int) c); case Color.Green: return String.Format("Green = {0}", (int) c); case Color.Blue: return String.Format("Blue = {0}", (int) c); default: return "Invalid color"; } } }

29. Output: Red = 0 Green = 10 Blue = 11 • Red is assigned 0 because it doesn’t have an initializer and it is the first member of the enumeration • Green is explicitly assigned 10 • Blue is assigned the value one greater than the member that precedes it in the declaration

30. Arrays There are five types of arrays in C#: single-dimensional multi-dimensional Jagged Rectangular and mixed.

31. Arrays array indexing starts at 0 fixed length or dynamic The elements are all the same type All C# arrays have a rank, which is basically regarded as the dimension of the array, or technically the number of indices associated with each element of the array. The elements of a C# array are all the same type, and this type is called the element type of the array. The elements of a C# array are all the same type, and this type is called the element type of the array.

32. Examples Arrays array of three elements of integer type: intArray = new int[3] {0, 1, 2}; dynamic array of string elements: string[] strArray = new string[] {"Benedryll", "Tayler", "sleep”, “yum”}; declares a multidimensional array: string[,] strArray; multidimensional array with a matrix of 2x2 int[,] numbers = new int[2,2]{{1,2},{2,3}}; Jagged arrays int[][] numArray = new int[][] { new int[] {1,3,5}, new int[] {2,4,6,8,10} };

33. Array Class in C# following are some of the built-in methods of the array class BinarySearch SetValue GetLength Sort GetLowerBound GetUpperBound IndexOf LastIndexOf BinarySearch -searches a one-dimensional sorted array for a value using a binary search algorithm SetValue- sets the specified items in an array to the specified value GetLength- returns the length of the array Sort -sorts items in a one-dimensional array GetLowerBound -returns the lower bound of an array, and GetUpperBound IndexOf -returns the index of the first occurrence of a specified item in an array or portion of an array. LastIndexOf -returns the index of the last occurrence of a specified item in an array or portion of an array. BinarySearch -searches a one-dimensional sorted array for a value using a binary search algorithm SetValue- sets the specified items in an array to the specified value GetLength- returns the length of the array Sort -sorts items in a one-dimensional array GetLowerBound -returns the lower bound of an array, and GetUpperBound IndexOf -returns the index of the first occurrence of a specified item in an array or portion of an array. LastIndexOf -returns the index of the last occurrence of a specified item in an array or portion of an array.

34. Arithmetic Expressions Binary Operations Just like C++ Includes operators: + , - , * , / , % Compiler uses implicit conversion Result either be double or float with decimals Supports Prefix and Postfix types ++x & --x x++ & x--

35. Arithmetic Expressions Cont. Supports unary operations Use minus sign to show negativity Plus sign does nothing to the value though Python – full support for arithmetic expressions C# - does not support all of them Ex: lacks a right shift with zero extension operator (>>>)

36. Arithmetic Expressions Cont. Uses the same semantics as Python Does include error checking for these expressions to watch for: Underflow Overflow Overflow has keywords: Checked - it will give you an arithmetic error Unchecked – it will ignore the overflow

37. Relational and Boolean Expressions Similar to most languages Supports: < , <= , > , >=, == , != Avoid writing expressions like: bool c = a = b; C++ allows to be compiled C# gives an error while compiling

38. Operator Overloading Supported as with Python and C++, but not Java Follows a stricter guideline than C++ methods with the overloads must be in the class that those methods are defined must have matching operators If you overload the ==, then you must do one for != public static bool operator ==(Score x,Score y) { return x.value == y.value; } public static bool operator !=(Score x,Score y) { return x.value != y.value; }

39. Operator Overloading Cont. Contains the keyword operator to use Must be declared under a static member function Same works for overloading Relational operators If you implement the + operator, then you will also need the += Makes sure operators that are logically paired are defined at compile time

40. Type Conversions Strongly typed language – safe side More typesafe than C++ Convert data and also object types Only implicitly converts what is considered a safe conversion No loss of data Widening of integers Derived type to a base type

41. Type Conversions Cont. Instances of implicit conversions: numerical, enumeration, reference and boxing conversions Boxing conversion changes a type to an object type makes a copy of the value being boxed refers to same instance when you box a ref type No Implicit conversions for: Boolean types and integers, enumeration members and integers, and no void pointers

42. Type Conversions Cont. Can not convert any type to a char type Example of converting to a 16 bit integer: double exFloat = 4.5; int x = 2; x = x + Convert.ToInt16(exFloat) ; - Value of x would be 6 Un-boxing – convert an object back to value Need a casting operator () with un-boxing Example of Boxing & Un-boxing: int i = 50; object o = i; //boxing conversion int j = (int) o; // un-boxing conversion

43. Selection Statements Supports if-else and switch statements If-else Ex: If (displayChar = = ‘S’){ Save(); } else if (displayChar = = ‘L’){ Load(); } else{ System.Console.Writeline(“Error Occurred”); } Works just like C++

44. Selection Statements Cont. Switch Statement – different than C++ and Python C# does not fall through by default Only way falls through – no instructions in case statement to say what to do next C# supports data types: Integral,char, enum, and string C++ and Java doesn’t support the string data type They require the keyword break to be used Makes C# less error prone for this reason

45. Selection Statements Cont. Example of string switch statement: switch(displayChar){ case ‘S’: Save(); case ‘L’: Load(); default: System.Console.Writeline(Error Occurred); } break statement is more of an implied one before each case

46. Iterative Statements Supports for, foreach, while, & do while for loop: serves same purpose as C++ except control expression is boolean foreach loop: provides advantage over C++ and Java ideal for working with collection classes very reliable Works for objects in collections including arrays Makes code shorter

47. Iterative Statements Cont. Compare C++ and C# with collections: Example in C++: while (! collection.isEmpty()) { Object o = collection.get(); collection.next(); } for (int i = 0; i < array.length; i++){} Example in C#: foreach (object o in collection){} foreach (int i in array){} C# code is much shorter and efficient

48. Iterative Statements Cont. While and do while – works same as C++ Same semantics Example of do while: int x = 5; do{ Console.WriteLine(x); x++; }while(x < 4); Would just output 5 Looping statements – contain a continue statement Terminates the innermost loop Similar to break – except break exits the loop

49. Unconditional Branching Supports the keywords: goto, break, continue, return, and throw Works basically the same as the other languages Throw statement - gives an exception usually with try-catch and try-finally statements Ex: if (s = = null){ throw(new ArgumentNullException()); }

50. Subprograms Doesn’t support generic parameters unlike C++ with its templates Do not need to declare their methods before being called Unlike C++ - must have prototypes for the declarations of the methods Allows overloaded subprograms – some are predefined Error prone – can create ambiguous program calls C# uses only methods – no functions Method can return any type or class Method itself can not be returned

51. Local Referencing Environment Local variables – not used before called Methods – only stack dynamic local variables Static in methods is not an option Parameter Passing Supports 4 types: pass by value, pass by reference, output parameters & parameter arrays Default – Pass by Value Use keyword ref to pass by reference Contrast to C++: must use ref when calling and declaring a method

52. Local Referencing Environment Cont. Example of swap using pass by reference: public static void Main (){ int x = 5; int y = 10; swap (ref x, ref y); Console.WriteLine(x); Console.WriteLine(y); } public static void swap (ref int x, ref int y) { int temp = x; x = y; y = temp; } Would output x as 10 and y as 5

53. Local Referencing Environment Cont. Output parameters Uses out keyword Assigns a value before returning Causes method to refer to same variable that was passed into method Same as pass by reference except variable doesnt have to be initialized Ideal for returning multiple values

54. Local Referencing Environment Cont. Example of Out-Mode: public static int exOut(out int x) { // x is unassigned // assigns the value of x x = 5; // value of x is now read int y = x; } public static void Main(){ // variable with no value int a; // passed as an output parameter with no value exOut(out a); // now assigned a value and is written out Console.WriteLine(a); }

55. Local Referencing Environment Cont. Parameter arrays Use several parameters Must be the same type Contains keyword params: Use with variable amount of parameters

56. Local Referencing Environment Cont. Example: public void ListParam (params int [] list) { // grabs each item out of the array foreach (int a in list){ Console.Write(a + “ “); } Console.WriteLine(); } public static void Main(string[] args){ // creates an array with 3 values int[] a = {5, 10, 15}; // calls ListParam with the array just created ListParam(a); // calls ListParam with 5 values ListParam(20, 25, 30, 35, 40); } output 5, 10, 15 on first ListParam call output 20, 25, 30, 35, 40 on second ListParam call

57. Object Orientation in C# Encapsulation Data Abstraction Data Organization

58. Encapsulation Classes Access Modifiers Properties Nested Types

59. The C# Class

65. Data Abstraction Abstract Classes Interfaces Structs Inheritance

66. As one can deduce from the code sample, the initialization is extremely similar to both Python and C++ in its syntactical and structural representation. Just as in Python, the use of colons to refer to the inherited class after the derived class is present. Similarly, in C++, one is forced to explicitly call the base class in order to initialize the inheritance, just as in C#. As one can deduce from the code sample, the initialization is extremely similar to both Python and C++ in its syntactical and structural representation. Just as in Python, the use of colons to refer to the inherited class after the derived class is present. Similarly, in C++, one is forced to explicitly call the base class in order to initialize the inheritance, just as in C#.

70. Data Organization Namespaces Assemblies

73. Exception Handling The Exception Class The Throw Statement Try & Catch Blocks The Finally Block Message Help Link Stack Trace

74. Found in the System namespace Used to throw and catch exceptions Also allows user-defined exceptions If an Exception is unhandled, the Exception Class executes by “unwinding the stack”

77. Links user to information about an exception and possible files that could help prevent such an exception. Displays the series of method calls that lead to the method where the exception was thrown.

78. Find Your Weather Program Allows user to enter zip code Weather.com website is parsed based on zip code Today’s and Tomorrow’s Weather is displayed

79. Find Your Weather Program

80. private static string HighToday(string strZip, ref string strHigh) { HttpWebRequest htreq; HttpWebResponse htres; StreamReader sreader; // website used to gather info string website = @"http://www.weather.com/weather/tenday/" + strZip; // string phrase to search for string strFindHigh = @"temph1="; strHigh = ""; try { /// requests Weather.com's website htreq = (HttpWebRequest)WebRequest.Create(website); /// executes the request htres = (HttpWebResponse)htreq.GetResponse(); /*Gets the response stream and makes it a string translate from bytes to ASCII text*/ sreader = new StreamReader(htres.GetResponseStream(), Encoding.ASCII); //keeps reading line from website till finds phrase temph1= while (strHigh.IndexOf(strFindHigh) == -1) { strHigh = sreader.ReadLine(); } // Closes the StreamReader sreader.Close(); // finds the substring within a string and gets the index of it strHigh = strHigh.Substring(strHigh.IndexOf(strFindHigh)); // finds the length of the substring strHigh = strHigh.Substring(strFindHigh.Length); /* gets the result you want by setting the index of substring as 0 and go till it finds the index of & */ strHigh = strHigh.Substring(0, strHigh.IndexOf("&")); } catch(Exception) { strHigh = "N/A"; } return strHigh; }

81. Tray Icon //must be used to Destroy the Tray Icon or else a memory leak would occur [DllImport("user32.dll", EntryPoint = "DestroyIcon")] static extern bool DestroyIcon(IntPtr convert); private void TrayIcon() { // Creates the Tray Icon to display the current temperature Bitmap bit; SolidBrush color; Graphics pic; IntPtr convert; Icon icon; string strTemperature = ""; string strLocalWeather = ""; string strFeels = ""; // Creates a Bitmap Image bit = new Bitmap(16, 16); /* Sets the color of the text to black by the FontDialog .net feature */ color = new SolidBrush(fontDialog1.Color); // Creates a Graphic Instance of the Bitmap pic = Graphics.FromImage(bit); // Calls the GetWeather method to get the current temperature GetWeather(ZipTextbox.Text, ref strTemperature, ref strLocalWeather, ref strFeels); // Uses the .Net feature to Draw the current temperature on the graphic instance pic.DrawString(strTemperature + "°", fontDialog1.Font, color, 0, 0); // Convert the bitmap into an Icon convert = bit.GetHicon(); icon = Icon.FromHandle(convert); // Sets the TrayIcon(called NotifyIcon) as the icon created notifyIcon1.Icon = icon; /* Must be called because GetHicon() creates an handle that must be destroyed */ DestroyIcon(convert); }

82. Main Method private void EnterButton_Click(object sender, EventArgs e) { // this: current instance of the class; sets the enter button as default this.AcceptButton = EnterButton; /* Sets the Groupboxes with all the Temp info to visible when clicked enter */ this.groupBox1.Visible = true; this.groupBox2.Visible = true; string strTemperature = ""; string strLocalWeather = ""; string strFeels = ""; string strCond = ""; string strHigh = ""; string strLow = ""; string strCondt = ""; string strHight = ""; string strLowt = ""; string strUpdate = ""; // Displays the Hour Glass Cursor this.Cursor = Cursors.WaitCursor; // Calls all the methods created to get info GetWeather(ZipTextbox.Text, ref strTemperature, ref strLocalWeather, ref strFeels); TodayCondition(ZipTextbox.Text, ref strCond); HighToday(ZipTextbox.Text, ref strHigh); LowToday(ZipTextbox.Text, ref strLow); TomCondition(ZipTextbox.Text, ref strCondt); HighTomorrow(ZipTextbox.Text, ref strHight); LowTomorrow(ZipTextbox.Text, ref strLowt); LastUpdate(ZipTextbox.Text, ref strUpdate); // Changes the Cursor back to the arrow this.Cursor = Cursors.Arrow; /* Sets the info gathered from the methods and sets them to display in the appropriate label */ LocalLabel.Text = strLocalWeather; ConditionLabel.Text = strCond; LowtLabel.Text = strLow + "°"; ConditiontLabel.Text = strCondt; UpdateLabel.Text = strUpdate; // Calls the Tray Icon Method to display the tray icon TrayIcon(); // Handles the exceptions when N/A is displayed if (strTemperature == "N/A"){ TempLabel.Text = "N/A"; } else{ TempLabel.Text = strTemperature + "°";

83. Find Your Weather Program

84. Game 2 player game Players take turns rolling the die Who ever reaches the end first wins The game can be restarted at any time using the restart button

85. Die Class class Dice_Class { // these are called feilds private int _sides = 6;// the die initaly has 6 sides private int _die_value ; // the die has no inital _die_value // theses are called properties public int sides { get { return _sides; } set { _sides = value; } } public int die_value { get { return _die_value; } set { _die_value = value;} } …….

  • Login