Download presentation
Presentation is loading. Please wait.
Published bySibyl Horn Modified over 9 years ago
1
Neal Stublen nstublen@jccc.edu
2
Tonight’s Agenda C# data types Control structures Methods and event handlers Exceptions and validation Q&A
4
Built-in Types Integer Types byte, sbyte, short, ushort, int, uint, long, ulong Floating Point Types float, double, decimal Character Type char (2 bytes!) Boolean Type bool ( true or false ) Aliases for.NET data types (Byte, Integer, Decimal, etc.)
5
Declare and Initialize ; int index; float interestRate; = ; int index = 0; float interestRate = 0.0005;
6
Constants const = ; const decimal PI = 3.1415926535897932384626; PI = 3.14; // error!!
7
Naming Conventions Camel Notation (camel-case) salesTax Common for variables Pascal Notation (title-case) SalesTax Common for type names and constants C or Python style sales_tax (variables) SALES_TAX (constants) Not common
8
Arithmetic Operators Addition (+) Subtraction (-) Multiplication (*) Division (/) Modulus (%) Increment (++) value++ or ++value Decrement (--) value-- or --value
9
Prefix and Postfix Operators Prefix operators modify a variable before it is evaluated Postfix operators modify a variable after it is evaluated y = 1; x = y++; // y = 2 // x = 1 (y was incremented AFTER evaluation) y = 1; x = ++y; // y = 2 // x = 2 (y was incremented BEFORE evaluation)
10
Assignment Operators Assignment (=) Addition (+=) x = x + y → x += y Subtraction (-=) Multiplication (*=) Division (/=) Modulus (%=)
11
Order of Precedence Increment, decrement Prefix versions Negation Multiplication, division, modulus Addition, subtraction Evaluate from left to right Evaluate innermost parentheses first
12
What Should Happen? int i = (54 – 15) / 13 - 7; int i = 39 / 13 - 7; = 3 - 7; = -4;
13
What Should Happen? int i = a++ * 4 – b; int i = (a * 4) - b; a = a + 1;
14
What Should Happen? int i = ++a * 4 – b; a = a + 1; int i = (a * 4) - b;
16
"Advanced" Math Operations The Math class provides a set of methods for common math operations totalDollars = Math.Round(totalDollars, 2); Rounds to nearest whole number hundred = Math.Pow(10, 2); ten = Math.Sqrt(100); one = Math.Min(1, 2); two = Math.Max(1, 2);
17
String Declarations // Simple declaration string text; // Initial value (double quotes) string text = "Hello!"; // Empty string string text = ""; // Unknown value (not an empty string) string text = null;
18
String Concatenation string text = "My name is "; text = text + "Neal" text += " Stublen.“ string first = "Neal"; string last = "Stublen"; string greeting = “Hi, " + first + " " + last; double grade = 94; string text = "My grade is " + grade + ".";
19
Special String Characters Escape sequence New line ("\n") Tab ("\t") Return ("\r") Quotation ("\"") Backslash ("\\") filename = "c:\\dev\\projects"; quote = "He said, \"Yes.\""; filename = @"c:\dev\projects"; quote = @"He said, ""Yes.""";
21
Type Casting Implicit Less precise to more precise byte->short->int->long->double Automatic casting to more precise types int letter = 'A'; int test = 96, hmwrk = 84; double avg = tests * 0.8 + hmwrk * 0.2;
22
Type Casting Explicit More precise to less precise int->char, double->float Must be specified to avoid compiler errors ( ) double total = 4.56; int avg = (int)(total / 10); decimal decValue = (decimal)avg;
23
What Should Happen? int i = 379; double d = 4.3; byte b = 2; double d2 = i * d / b; int i2 = i * d / b;
24
Converting Types To Strings Everything has a ToString() method.ToString(); int i = 5; string s = i.ToString(); // s = "5“ double d = 5.3; string s = d.ToString(); // s = "5.3"
25
Converting Strings To Types Use the data type’s Parse() method.Parse( ); ○ decimal m = Decimal.Parse("5.3"); Use the Convert class Convert.ToInt32( ); ○ int i = Convert.ToInt32(" Convert.ToBool( ); Convert.ToString( );...
26
Formatted Strings Formatting codes can customize the output of ToString().ToString( ); amount.ToString("c"); // $43.16 rate.ToString("p1"); // 3.4% count.ToString("n0"); // 2,345 See p. 121 for formatting codes
27
Formatted Strings String class provides a static Format method {index:formatCode} String.Format("{0:c}", 43.16); ○ // $43.16 String.Format("{0:p1}", 0.034); ○ // 3.4%
28
Formatted Strings String.Format( "Look: {0:c}, {1:p1}", 43.16, 0.034); // Look: $43.16, 3.4% String.Format( “{0}, your score is {1}.", name, score); // John, your score is 34.
29
Variable Scope Scope limits access and lifetime Class scope Method scope Block scope No officially "global" scope
30
Enumeration Types Enumerations define types with a fixed number of values enum StoplightColors { Red, Yellow, Green }
31
Enumeration Type Numeric values are implied for each enumerated value enum StoplightColors { Red = 10, Yellow, Green }
32
Enumeration Type enum StoplightColors { Red = 10, Yellow = 20, Green = 30 }
33
Enumeration Type enum StoplightColors { Red = 10 } string color = StoplightColors.Red.ToString(); // color = "Red", not "10"
34
"null" Values Identifies an unknown value string text = null; int value = null; // error! int? nonValue = null; bool defined = nonValue.HasValue; int value = nonValue.Value; decimal? price1 = 19.95m; decimal? price2 = null; decimal? total = price1 + price2; total = null (unknown, which seems intuitive)
36
Form Enhancements Display a formatted subtotal as a currency Round the discount amount to two decimal places Keep running invoice totals Reset the totals when the button is clicked Chapter 4 exercises
38
Common Control Structures Boolean expressions Evaluate to true or false Conditional statements Conditional execution Loops Repeated execution
39
Boolean Expressions Equality (==) a == b Inequality (!=) a != b Greater than (>) a > b Less than (<) a < b Greater than or equal (>=) a >= b Less than (<=) a <= b
40
Logical Operators Combine logical operations Conditional-And (&&) (file != null) && file.IsOpen Conditional-Or (||) (key == 'q') || (key == 'Q') And (&) file1.Close() & file2.Close() Or (|) file1.Close() | file2.Close() Not (!) !file.Open()
41
Logical Equivalence DeMorgan's Theorem !(a && b) is the equivalent of (!a || !b) !(a || b) is the equivalent of (!a && !b)
42
if-else Statements if (color == SignalColors.Red) { Stop(); } else if (color == SignalColors.Yellow) { Evaluate(); } else { Drive(); }
43
switch Statements switch (color) { case SignalColors.Red: { Stop(); break; } case SignalColors.Yellow: { Evaluate(); break; } default: { Drive(); break; }
44
switch Statements switch (color) { case SignalColors.Red: { Stop(); break; } case SignalColors.Yellow: // fall through default: { Drive(); break; }
45
switch Statements switch (color) { case SignalColors.Red: // fall through case SignalColors.Yellow: // fall through default: { Drive(); break; }
46
switch Statements switch (name) { case "John": case "Johnny": case "Jon": {... break; }
48
Form Enhancements Select a discount tier based on the customer type Chapter 5 exercises
49
while Statements while (!file.Eof) { file.ReadByte(); } char ch; do { ch = file.ReadChar(); } while (ch != 'q');
50
for Statements int factorial = 1; for (int i = 2; i <= value; ++i) { factorial *= i; } string digits = "" for (char ch = '9'; ch <= '0'; ch-=1) { digits += ch; }
51
break and continue Statements break allows is to jump out of a loop before reaching its normal termination condition continue allows us to jump to the next iteration of a loop
52
break and continue Statements string text = ""; for (int i = 0; i < 10; i++) { if (i % 2 == 0) continue; if (i > 8) break; text += i.ToString(); }
53
Caution! int index = 0; while (++index < lastIndex) { TestIndex(index); } int index = 0; while (index++ < lastIndex) { TestIndex(index); }
54
What About This? for (int i = 0; i < 10; i++) { } for (int i = 0; i < 10; ++i) { }
56
Debugging Summary Stepping through code (over, into, out) Setting breakpoints Conditional breakpoints
58
Form Enhancements Examine the looping calculation in the Future Value example Chapter 5 exercises
60
Class Methods class DiscountCalculator { private decimal CalcDiscPercent(decimal inAmt) { return (inAmt > 250.0m) ? 0.10m: 0.0m; } public decimal CalcDiscAmount(decimal inAmt) { decimal percent = CalcDiscPercent(inAmt); return inAmt * percent; }
61
Access Modifier class DiscountCalculator { private decimal CalcDiscPercent(decimal inAmt) { return (inAmt > 250.0m) ? 0.10m: 0.0m; } public decimal CalcDiscAmount(decimal inAmt) { decimal percent = CalcDiscPercent(inAmt); return inAmt * percent; }
62
Return Type class DiscountCalculator { private decimal CalcDiscPercent(decimal inAmt) { return (inAmt > 250.0m) ? 0.10m: 0.0m; } public decimal CalcDiscAmount(decimal inAmt) { decimal percent = CalcDiscPercent(inAmt); return inAmt * percent; }
63
Method Name class DiscountCalculator { private decimal CalcDiscPercent(decimal inAmt) { return (inAmt > 250.0m) ? 0.10m: 0.0m; } public decimal CalcDiscAmount(decimal inAmt) { decimal percent = CalcDiscPercent(inAmt); return inAmt * percent; }
64
Method Parameters class DiscountCalculator { private decimal CalcDiscPercent(decimal inAmt) { return (inAmt > 250.0m) ? 0.10m: 0.0m; } public decimal CalcDiscAmount(decimal inAmt) { decimal percent = CalcDiscPercent(inAmt); return inAmt * percent; }
65
Return Statements class DiscountCalculator { private decimal CalcDiscPercent(decimal inAmt) { return (inAmt > 250.0m) ? 0.10m: 0.0m; } public decimal CalcDiscAmount(decimal inAmt) { decimal percent = CalcDiscPercent(inAmt); return inAmt * percent; }
67
Parameters Summary Pass zero or more parameters Parameters can be optional Optional parameters are "pre-defined" using constant values Optional parameters can be passed by position or name Recommendation: Use optional parameters cautiously
68
Parameters Summary Parameters are usually passed by value Parameters can be passed by reference Reference parameters can change the value of the variable that was passed into the method
70
Event and Delegate Summary A delegate connects an event to an event handler. The delegate specifies the handler’s return type and parameters. Event handlers can be shared with multiple controls Chapter 6, Exercise 1 Clear result when any value changes
72
Exceptions Exception Format ExceptionArithmetic ExceptionOverflowExceptionDivideByZeroException
73
Format Exception string value = “ABCDEF”; int number = Convert.ToInt32(value);
74
Overflow Exception checked { byte value = 200; value += 200; int temp = 5000; byte check = (byte)temp; }
75
“Catching” an Exception try { int dividend = 20; int divisor = 0; int quotient = dividend / divisor; int next = quotient + 1; } catch { }
76
Responding to Exceptions A simple message box: MessageBox.Show(message, title); Set control focus: txtNumber.Focus();
77
Catching Multiple Exceptions try {} catch(FormatException e) { } catch(OverflowException e) { } catch(Exception e) { } finally { }
78
Throwing an Exception throw new Exception(“Really bad error!”); try { } catch(FormatException e) { throw e; }
80
Form Enhancements What exceptions might occur in the future value calculation? Chapter 7 exercises
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.