Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 C#. 2 C#’s Family Tree C# inherits a rich programming legacy from C (1972) and C++ (1979). It is closely related to Java (1991).

Similar presentations


Presentation on theme: "1 C#. 2 C#’s Family Tree C# inherits a rich programming legacy from C (1972) and C++ (1979). It is closely related to Java (1991)."— Presentation transcript:

1 1 C#

2 2 C#’s Family Tree C# inherits a rich programming legacy from C (1972) and C++ (1979). It is closely related to Java (1991).

3 3 A Faster Start C# does NOT require the use of pointers, object destructors, and the use of #include Command prompt or Visual Studio IDE No String[] args needed in main method header as in Java (optional) Class name does not have to match file name Can use.exe name to execute in the command line interface File can contain multiple classes

4 4 Object Oriented Language Methods and variables in object-oriented programming are encapsulated, that is, users are only required to understand the interface and not the internal workings of the class Polymorphism and Inheritance are two distinguishing features in the object-oriented programming approach Polymorphism describes the ability to create methods that act appropriately depending the context Inheritance provides the ability to extend a class so as to create a more specific class

5 5 Similarities and Differences from C++ and Java Functions are called Methods main() becomes Main() Namespace - class - object - method relationship introduced early Save files with.cs extension writeln() becomes WriteLine() Hello.cs Hello2.cs

6 6 Writing a C# Program that Produces Output “This is my first C# program” is a literal string of characters The string appears in parenthesis because it is a parameter or an argument The WriteLine() method prints a line of output on the screen

7 7 Writing a C# Program that Produces Output Out is an object that represents the screen The Out object was created and endowed with the method WriteLine() Not all objects have the WriteLine() method

8 8 Writing a C# Program that Produces Output Console is a class Console defines the attributes of a collection of similar “Console” objects

9 9 Writing a C# Program that Produces Output System is a namespace, which is a scheme that provides a way to group similar classes Namespaces are used to organize classes

10 10 After creating source code, you must do the following before you can view the program output: –Compile the source code into intermediate language (IL) –Use the C# just in time (JIT) compiler to translate the intermediate code into executable statements Compiling and Executing a Program from the Command Line

11 11 Every method used in C# must be part of a class A C# class name or identifier must meet the basic following requirements: –An identifier must begin with an underscore or a letter –An identifier can contain only letters or digits, not special characters #,$, or & –An identifier cannot be a C# reserved keyword Selecting Identifiers

12 12 Variables All variables are objects As objects, all types have built-in methods Creating formatted output is easy Variables.cs Characters are not one byte, they are two bytes due to Unicode (0 to 65535)Unicode Global Portability

13 13 Data Types byte1 byteRange 0 to 255 Unsigned byte sbyte1 byteRange -128 to 127 Signed byte short2 bytesRange -32768 to 32767 Signed short ushort2 bytesRange 0 to 65535 Unsigned short

14 14 More Integer Data Types int4 bytesRange -2,147,483,647 to 2,147,483,647 Signed integer uint4 bytesRange 0 to 4,294,967,295 Unsigned integer long8 bytesGreater than ±900,000 trillion Signed long int ulong8 bytesGreater than 18 million trillion Unsigned long int

15 15 Other Data Types float4 bytesRange A number 38 zeros long Float number double8 bytes Range A number 308 zeros long Double precision decimal8 bytes Range A number 28 zeros long Fixed precision stringN/ARange N/A Unicode char2 bytes Range 0x0000 to 0xFFFF Unicode character boolTrue or False Boolean

16 16 Using the String Type The Equals Method returns True or False The Compares Method returns a zero if two words are the same, a positive number if the first word is greater than the second, and a negative number if the first word is less than the second. Strings.cs

17 17 New Data Types byte = 1 byte Range = 0 to 255 sbyte = 1 byte Range = -128 to 128 Decimal – for monetary calculations –Range 1E - 28 to 7.9E + 28 Decimal.cs –C++ often was subject to a variety of rounding errors. The decimal data type can accurately represent up to 28 decimal points.

18 18 Formatting Output Format Character DescriptionDefault Format (if no precision is given) C or cCurrency($##,###.##) D or dDecimal[-]######## E or eScientific (exponential) [-]#.#######E+### [-]#.######e+### F or fFixed Point[-]########.##

19 19 Example of Formatting Console.WriteLine(“Floating Amount: {0,0:$###.##}, 3.14); Prints: Floating Amount: $3.14 Console.WriteLine(“Floating Zeros: {0,0:$000.00}, 3.14); Prints: Floating Amount: $003.14

20 20 Format Character DescriptionDefault Format (if no precision is given) G or gGeneralEither general or scientific N or nNumber[-]##,###.## P or pPercent Represents a passed numeric value as a % R or rRound trip Ensures that numbers converted to strings will have the same value when they are converted back into numbers X or xHexadecimal Minimum hexadecimal (base 16) Formatting Output Cont.

21 21 Examples of Formatting double someMoney = 123; string moneyString; moneyString = someMoney.ToString("F"); Console.WriteLine(moneyString); moneyString = someMoney.ToString("F3"); Console.WriteLine(moneyString); Console.WriteLine(someMoney.toString("C2") The first WriteLine() statement in the following code produces 123.00, the second produces 123.000, and the third produce $123.00.

22 22 Using the string Data Type to Accept Console Input You can use the Console.ReadLine() method to accept user input from the keyboard. This method accepts all the characters a user enters until the user presses Enter. The characters can be assigned to a string. For example, the statement: myString = Console.ReadLine(); accepts a user’s input and stores it in the variable myString.

23 23 Boolean Variables Values are true/false (no 1/0 like C++) If statements must use == for equivalency If you fail to use ==, it will not compile –Attempting to use an uninitialized variable If.cs

24 24 Relational Operators

25 25 Escape Sequences

26 26 Time for You to Try! Temperature Conversion Program Allow the User to Input a Fahrenheit temperature and convert it to Celsius Result should go out 2 decimal places Formula = (F - 32) x (5/9) Test Data = 90° F is 32° C

27 27 If Statement Like C++ and Java IfElseDecision.cs IfElseDecisionWithInput.cs Comments can be written 3 ways –/* The old C way –Block Comments */ –// The C++ way – Line Comments –/// The XML way

28 28 Logical Operators

29 29 The switch structure uses four new keywords: –switch starts the structure and is followed immediately by a test expression –case is followed by one of the possible values that might equal the switch expression –break optionally terminates a switch structure at the end of each case –default optionally is used prior to any action that should occur if the test expression does not match any case Making Decisions Using the switch Statement

30 30 Switch Statement No fall-through rule Switch.cs

31 31 Loops While Loop Do While Loop For Loop A loop is a structure that allows repeated execution of a block of statements

32 32 Using the while Loop You can use a while loop to execute a body of statements continuously while some condition continues to be true A while loop consists of the keyword while, followed by a Boolean expression within parentheses, followed by the body of the loop A loop that never ends is called an infinite loop

33 33 Using the while Loop To make a while loop end, three separate actions should occur: –Some variable, the loop control variable, is initialized –The loop control variable is tested in the while statement –The body of the while statement must take some action that alters the value of the loop control variable

34 34 Using the for Loop A loop that executes a specific number of times is a definite loop or a counter loop When you use a for statement, you can indicate the starting value for the loop control variable, the test condition that controls loop entry, and the expression that alters the loop control variable

35 35 Using the for Loop The three semicolon separated sections of a for statement are used for: –Initializing the loop control variable –Testing the loop control variable –Updating the loop control variable

36 36 Using the for Loop Printing integers 1 through 10 with while and for loops

37 37 Methods All methods must have an explicit return type No int default when returning variables Methods can have four types of arguments: ValueParameterDemo1.csParameterDemo1.cs ReferenceParameterDemo2.csParameterDemo2.cs OutputParameterDemo3.csParameterDemo3.cs ParamsParameterDemo4.csParameterDemo4.cs

38 38 Overloading Methods Overloading involves using one term to indicate diverse meanings When you overload a C# method, you write multiple methods with a shared name The compiler understands the meaning based on the arguments you use with the method

39 39 Overloading Methods An overloaded method

40 40 Arrays, like object fields, have default values You can assign nondefault values to array elements upon creation Examples: int[] myScores = new int[5] {100,76,88,100,90}; int[] myScores = new int[] {100,76,88,100,90}; int[] myScores = {100,76,88,100,90}; Initializing an Array

41 41 Arrays Arrays must be declared with brackets after the type: int[] numbers = new int[20];  Can use foreach statement (like VB) ForEach.cs  Params Params.cs

42 42 Arrays "Extra" array elements are not initialized to 0 IndexOutOfBoundsException becomes IndexOutOfRangeException You can change an array's size int[] nums = new int[5]; nums = new int[10];

43 43 Garbage Collection No need for a delete command to clear up dynamic arrays C#’s garbage collection reclaims object space automatically behind the scenes For efficiency, C# only runs the garbage collection feature when: –There are objects to recycle –There is a need to recycle them

44 44 The BinarySearch() Method The BinarySearch() method finds a requested value in a sorted array This method accepts two arguments: an array, and the field to be searched for The method returns –1 if the value is not found in the array, otherwise it returns the index where the value is located

45 45 The BinarySearch() Method This method does NOT work under the following conditions: –If the array items are not arranged in ascending order, the BinarySearch() method does not work correctly –If the array holds duplicated values, then the BinarySearch may not work –If you want to find a range match rather that an exact match, the BinarySearch() method does not work

46 46 The BinarySearch() Method BinarySearch program

47 47 Using the Sort() and Reverse() Methods The Sort() method arranges array items in ascending order

48 48 Using the Sort() and Reverse() Methods The Reverse() method reverses the order of items in an array

49 49 Using the Sort() and Reverse() Methods Output of MyTestScores

50 50 Classes Static members cannot be used with objects Built-in components have "natural" names - e.g., Label, not JLabel No multiple constructors for components like Label, Button, etc.

51 51 Understanding the this Reference When instances of a class are created, the resulting objects require separate memory locations in the computer In the following code, each object of Book would at least require separate memory locations for title, numPages, and Price

52 52 Understanding the this Reference Unlike the class fields that are unique to each instance, the methods of the class are shared Although the methods are shared, there must be a difference between two method calls (from different objects), because each returns a different value (based on their unique fields) When a method is called, you automatically pass a reference to the memory of the object into the method The implicitly passed reference is the this reference

53 53 Understanding the this Reference Book class methods explicitly using this reference

54 54 Understanding the this Reference Book class method that requires explicit this reference

55 55 Understanding Constructor Methods A constructor method is a method that establishes an object Every class created is automatically supplied with a public constructor method with no parameters Any constructor method you write must have the same name as its class, and constructor methods cannot have a return type

56 56 Inheritance Use a colon (not "extends" or "implements") Classes can appear in any order and within the same file (no forward references) When child class method overrides parent class method you must use the keyword new or override

57 57 When you create a class that is an extension or child of another class, you use a single colon between the derived class name and its base class name Extending Classes


Download ppt "1 C#. 2 C#’s Family Tree C# inherits a rich programming legacy from C (1972) and C++ (1979). It is closely related to Java (1991)."

Similar presentations


Ads by Google