Presentation is loading. Please wait.

Presentation is loading. Please wait.

C# Introduction ISYS 512. Major Differences Between VB Project and C# Project The execution starts from the Main method which is found in the Program.cs.

Similar presentations


Presentation on theme: "C# Introduction ISYS 512. Major Differences Between VB Project and C# Project The execution starts from the Main method which is found in the Program.cs."— Presentation transcript:

1 C# Introduction ISYS 512

2 Major Differences Between VB Project and C# Project The execution starts from the Main method which is found in the Program.cs file. – Solution/Program.cs – Contain the startup code Example: Application.Run(new Form1()); The Code window does not have the dropdown list for a control’s event. An event-procedure does not have the Handle clause.

3 Variable Names A variable name identifies a variable Always choose a meaningful name for variables Basic naming conventions are: – the first character must be a letter (upper or lowercase) or an underscore (_) – the name cannot contain spaces – do not use C# keywords or reserved words

4 Declare a Variable (case sensitive) DataType VaraibleName; Data type: – string Variables: string empName; string firstName, lastAddress, fullName; String concatenation: – fullName = firstName + lastName; – MessageBox.Show(“Total is “ + 25.75); – numeric variables: int, double, decimal double mydouble=12.7, rate=0.07;

5 The decimal Data Type In C#, the decimal keyword indicates a 128-bit data type (16 bytes). Compared to double types, it has more precision and a smaller range, which makes it appropriate for financial and monetary calculations. Be sure to add the letter M (or m) to a decimal value: decimal payRate = 28.75m; decimal price = 8.95M;

6 Explicit Conversion with Cast Operators C# allows you to explicitly convert among types, which is known as type casting You can use the cast operator which is simply a pair of parentheses with the type keyword in it int wholeNumber; decimal moneyNumber = 4500m; wholeNumber = (int) moneynumber; double realNumber; decimal moneyNUmber = 625.70m; realNumber = (double) moneyNumber; moneyNumber=(decimal) realNumber; Note: All variables come with a ToString() method.

7 Performing Calculations Basic calculations such as arithmetic calculation can be performed by math operators OperatorName of the operatorDescription +AdditionAdds two numbers -SubtractionSubtracts one number from another *MultiplicationMultiplies one number by another /DivisionDivides one number by another and gives the quotient %ModulusDivides one number by another and gives the remainder Other calculations: Use Math class’s methods.

8 Inputting and Outputting Numeric Values Input collected from the keyboard are considered combinations of characters (or string literals) even if they look like a number to you A TextBox control reads keyboard input, such as 25.65. However, the TextBox treats it as a string, not a number. In C#, use the following Parse methods to convert string to numeric data types – int.Parse – double.Parse – decimal.Parse Examples: int hoursWorked = int.Parse(hoursWorkedTextBox1.Text); double temperature = double.Parse(temperatureTextBox.Text); Note: We can also use the.Net’s Convert class methods: ToDouble, ToInt, ToDecimal: Example: hoursWorded = Convert.ToDouble(textBox1.Text);

9 Formatting Numbers with the ToString Method The ToString method can optionally format a number to appear in a specific way The following table lists the “format strings” and how they work with sample outputs Format String DescriptionNumberToString()Result “N” or “n”Number format12.3ToString(“n3”)12.300 “F” or “f”Fixed-point scientific format123456.0ToString("f2")123456.00 “E” or “e”Exponential scientific format123456.0ToString("e3")1.235e+005 “C” or “c”Currency format-1234567.8ToString("C")($1,234,567.80) “P” or “p”Percentage format.234ToString("P")23.40%

10 Working with DateTime Data Declare DateTime variable: – Example: DateTime mydate; Convert date entered in a textbox to DateTime data: – Use Convert: mydate = Convert.ToDateTime(textBox1.Text); – Use DateTime class Parse method: mydate = DateTime.Parse(textBox1.Text); DateTime class reference: – http://msdn.microsoft.com/en- us/library/system.datetime.aspx http://msdn.microsoft.com/en- us/library/system.datetime.aspx – http://msdn.microsoft.com/en-us/library/cc165448.aspx

11 Throwing an Exception I n the following example, the user may entered invalid data (e.g. null) to the milesText control. In this case, an exception happens (which is commonly said to “throw an exception”). The program then jumps to the catch block. You can use the following to display an exception’s default error message: catch (Exception ex) { MessageBox.Show(ex.Message); } try { double miles; double gallons; double mpg; miles = double.Parse(milesTextBox.Text); gallons = double.Parse(gallonsTextBox.Text); mpg = miles / gallons; mpgLabel.Text = mpg.ToString(); } catch { MessageBox.Show("Invalid data was entered."): }

12 Decision Structure The flowchart is a single-alternative decision structure It provides only one alternative path of execution In C#, you can use the if statement to write such structures. A generic format is: if (expression) { Statements; etc.; } The expression is a Boolean expression that can be evaluated as either true or false Cold outside Wear a coat True False

13 Relational Operators A relational operator determines whether a specific relationship exists between two values OperatorMeaningExpressionMeaning >Greater thanx > yIs x greater than y? <Less thanx < yIs x less than y? >=Greater than or equal tox >= yIs x greater than or equal to y? <=Less than or equal tox <= yIs x less than or equal to you? ==Equal tox == yIs x equal to y? !=Not equal tox != yIs x not equal to you?

14 The if-else statement An if-else statement will execute one block of statement if its Boolean expression is true or another block if its Boolean expression is false It has two parts: an if clause and an else clause In C#, a generic format looks: if (expression) { statements; } else { statements; }

15 The if-else-if Statement You can also create a decision structure that evaluates multiple conditions to make the final decision using the if-else-if statement In C#, the generic format is: if (expression) { } else if (expression) { } else if (expression) { } … else { } int grade = double.Parse(textBox1.Text); if (grade >=90) { MessageBox.Show("A"); } else if (grade >=80) { MessageBox.Show("B"); } else if (grade >=70) { MessageBox.Show("C"); } else if (grade >=60) { MessageBox.Show("D"); } else { MessageBox.Show("F"); }

16 Logical Operators The logical AND operator (&&) and the logical OR operator (||) allow you to connect multiple Boolean expressions to create a compound expression The logical NOT operator (!) reverses the truth of a Boolean expression OperatorMeaningDescription &&ANDBoth subexpression must be true for the compound expression to be true ||OROne or both subexpression must be true for the compound expression to be true !NOTIt negates (reverses) the value to its opposite one. ExpressionMeaning x >y && a < bIs x greater than y AND is a less than b? x == y || x == zIs x equal to y OR is x equal to z? ! (x > y)Is the expression x > y NOT true?

17 Sample Decision Structures with Logical Operators The && operator if (temperature 12) { MessageBox.Show(“The temperature is in the danger zone.”); } The || operator if (temperature 100) { MessageBox.Show(“The temperature is in the danger zone.”); } The ! Operator if (!(temperature > 100)) { MessageBox.Show(“The is below the maximum temperature.”); }

18 Boolean (bool) Variables and Flags You can store the values true or false in bool variables, which are commonly used as flags A flag is a variable that signals when some condition exists in the program – False – indicates the condition does not exist – True – indicates the condition exists Boolean good; // bool good; if (mydate.Year == 2011) { good = true; } else { good = false; } MessageBox.Show(good.ToString());

19 Sample switch Statement switch (month) { case 1: MessageBox.Show(“January”); break; case 2: MessageBox.Show(“February”); break; case 3: MessageBox.Show(“March”); break; default: MessageBox.Show(“Error: Invalid month”); break; } month Display “January” Display “February” Display “March” Display “Error: Invalid month”

20 Structure of a while Loop In C#, the generic format of a while loop is: while (BooleanExpression) { Statements; } Example: while (count < 5) { counter = count + 1; // counter ++; } MessageBox.Show(counter.ToString());

21 The for Loop The for loop is specially designed for situations requiring a counter variable to control the number of times that a loop iterates You must specify three actions: – Initialization: a one-time expression that defines the initial value of the counter – Test: A Boolean expression to be tested. If true, the loop iterates. – Update: increase or decrease the value of the counter A generic form is: for (initializationExpress; testExpression; updateExpression) { } The for loop is a pretest loop

22 Sample Code int count; for (count = 1; count <= 5; count++) { MessageBox.Show(“Hello”); } The initialization expression assign 1 to the count variable The expression count <=5 is tested. If true, continue to display the message. The update expression add 1 to the count variable Start the loop over // declare count variable in initialization expression for (int count = 1; count <= 5; count++) { MessageBox.Show(“Hello”); }

23 Other Forms of Update Expression In the update expression, the counter variable is typically incremented by 1. But, this is not a requirement. //increment by 10 for (int count = 0; count <=100; count += 10) { MessageBox.Show(count.ToString()); } You can decrement the counter variable to make it count backward //counting backward for (int count = 10; count >=0; count--) { MessageBox.Show(count.ToString()); }

24 The do-while Loop The do-while loop is a posttest loop, which means it performs an iteration before testing its Boolean expression. In the flowchart, one or more statements are executed before a Boolean expression is tested A generic format is: do { statement(s); } while (BooleanExpression); Boolean Expression Statement(s) True False

25 Introduction to Methods Methods can be used to break a complex program into small, manageable pieces – This approach is known as divide and conquer – In general terms, breaking down a program to smaller units of code, such as methods, is known as modularization Two types of methods are: – A void method simply executes a group of statements and then terminates – A value-returning method returns a value to the statement that called it

26 void Methods A void method simply executes the statement it contains and then terminates. It does not return any value to the statement that called it To create a method you write its definitions A method definition has two parts: – header: the method header appears at the beginning of a method definition to indicate access mode, return type, and method name – body: the method body is a collection of statements that are performed when the method is executed

27 Void Method The book separates a method header into four parts : – Access modifier: keywords that defines the access control private: a private method can be called only by code inside the same class as the method public: a public method can be called by code that is outside the class. – Return type: specifies whether or not a method returns a value – Method name: the identifier of the method; must be unique in a given program. This book uses Pascal case (aka camelCase) – Parentheses: A method’s name is always followed by a pair of parentheses private void DisplayMessage() { MessageBox.Show(“This is the DisplayMessage method.”); } Access modifier Return type Method name Parentheses

28 Value-Returning Methods (Functions) In C# the generic format is: AccessModifier DataType MethodName(ParameterList) { statement(s); return expression; } AccessModifier: private or public DataType: int, double, decimal, string, and Boolean MethodName: the identifier of the method; must be unique in a program ParameterList: an optional list of parameter Expression: can be any value, variable, or expression that has a value A return statement is used to return a value to the statement that called the method.

29 Passing Arguments to Methods By Value Example: private void DisplayValue(int value) { MessageBox.Show(value.ToString()); } int x = 5; DisplayValue(x); DisplayValue(x * 4);

30 Passing Arguments by Reference A reference parameter is a special type of parameter that does not receive a copy of the argument’s value It becomes a reference to the argument that was passed into it When an argument is passed by reference to a method, the method can change the value of the argument in the calling part of the program In C#, you declare a reference parameter by writing the ref keyword before the parameter variable’s data type private void SetToZero(ref int number) { number =0; } To call a method that has a reference parameter, you also use the keyword ref before the argument int myVar = 99; SetToZero(ref myVar);


Download ppt "C# Introduction ISYS 512. Major Differences Between VB Project and C# Project The execution starts from the Main method which is found in the Program.cs."

Similar presentations


Ads by Google