490 likes | 606 Vues
This guide introduces developers to fundamental concepts in C#, covering built-in data types, including integers, floating-point numbers, characters, and booleans. Learn about variable declaration, initialization, constants, and naming conventions, as well as arithmetic and assignment operators. Explore type casting, advanced math operations, strings, and special character sequences. The guide also covers variable scope, enumeration types, control structures, and logical operators. Ideal for those starting in C# programming or seeking a refresher.
E N D
Neal Stublen nstublen@jccc.edu C#: Introduction for Developers
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.)
Declare and Initialize <type> <variableName>; int index; float interestRate; <type> <variableName> = <value>; int index = 0; float interestRate = 0.0005;
Constants const <type> <variableName> = <value>; const decimal PI = 3.1415926535897932384626;
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 (variable) • SALES_TAX (constant) • Not common
Arithmetic Operators • Addition (+) • Subtraction (-) • Multiplication (*) • Division (/) • Modulus (%) • Increment (++) • Decrement (--)
Assignment Operators • Assignment (=) • Addition (+=) • Subtraction (-=) • Multiplication (*=) • Division (/=) • Modulus (%=)
Type Casting • Implicit • Less precise to more precise • byte->short->int->long->double int letter = 'A';int test = 96, hwrk = 84;double avg = test * 0.8 + hwrk * 0.2;
Type Casting • Explicit • More precise to less precise • int->char, double->float (<type>) <expression> double total = 4.56; intavg = (int)(total / 10); decimal decValue = (decimal)avg;
What Should Happen? inti = 379; double d = 4.3; byte b = 2; double d2 = i * d / b; int i2 = i * d / b;
"Advanced" Math Operations • totalDollars = Math.Round(totalDollars, 2); • hundred = Math.Pow(10, 2); • ten = Math.Sqrt(100); • one = Math.Min(1, 2); • two = Math.Max(1, 2);
Strings • string text = "My name is "; • text = text + "Neal" • text += " Stublen." • double grade = 94; • string text = "My grade is " + grade + “.”;
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.""";
Converting Types • <value>.ToString(); • <type>.Parse(<string>); • Convert.ToBool(<value>); • Convert.ToString(<value>); • Convert.ToInt32(<value>);
Formatted Strings • <value>.ToString(<formatString>); • amount.ToString("c"); // $43.16 • rate.ToString("p1"); // 3.4% • count.ToString("n0"); // 2,345 • String.Format("{0:c}", 43.16); // $43.16 • String.Format("{0:p1}", 0.034); // 3.4% • See p. 121 for formatting codes
Variable Scope • Scope limits access and lifetime • Class scope • Method scope • Block scope • No officially "global" scope
Enumeration Type enum StoplightColors { Red, Yellow, Green }
Enumeration Type enum StoplightColors { Red = 10, Yellow, Green }
Enumeration Type enum StoplightColors { Red = 10, Yellow = 20, Green = 30 }
Enumeration Type enum StoplightColors { Red = 10 } string color = StoplightColors.Red.ToString();
"null" Values • Identifies an unknown value • string text = null; • int? nonValue = null; • bool defined = nonValue.HasValue; • int value = nonValue.Value; • decimal? price1 = 19.95; • decimal? price2 = null; • decimal? total = price1 + price2;
Control Structures • Boolean expressions • Evaluate to true or false • Conditional statements • Conditional execution • Loops • Repeated execution
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
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()
Logical Equivalence • DeMorgan's Theorem • !(a && b) is the equivalent of (!a || !b) • !(a || b) is the equivalent of (!a && !b)
if-else Statements if (color == SignalColors.Red) { Stop(); } else if (color == SignalColors.Yellow) { Evaluate(); } else if (color == SignalColors.Green) { Drive(); }
switch Statements switch (color ) { case SignalColors.Red: { Stop(); break; } case SignalColors.Yellow: { Evaluate(); break; } default: { Drive(); break; } }
while Statements while (!file.Eof) { file.ReadByte(); } char ch; do { ch = file.ReadChar(); } while (ch != 'q');
for Statements int factorial = 1; for (inti = 2; i <= value; ++i) { factorial *= i; } string digits = "" for (char ch = '9'; ch <= '0'; ch-=1) { digits += ch; }
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(); }
Caution! int index = 0; while (++index < lastIndex) { TestIndex(index); } int index = 0; while (index++ < lastIndex) { TestIndex(index); }
What About This? for (int i = 0; i < 10; i++) { } for (int i = 0; i < 10; ++i) { }
Debugging Summary • Stepping through code (over, into, out) • Setting breakpoints • Conditional breakpoints
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; } }
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
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
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
Exceptions Exception Format Exception Format Exception Arithmetic Exception Arithmetic Exception
Format Exception string value = “ABCDEF”; int number = Convert.ToInt32(value);
Overflow Exception checked { byte value = 200; value += 200; int temp = 5000; byte check = (byte)temp; }
“Catching” an Exception try { int dividend = 20; int divisor = 0; int quotient = dividend / divisor; int next = quotient + 1; } catch { }
Responding to Exceptions • A simple message box: • MessageBox.Show(message, title); • Set control focus: • txtNumber.Focus();
Catching Multiple Exceptions try {} catch( FormatException e) { } catch(OverflowException e) { } catch(Exception e) { } finally { }
Throwing an Exception throw new Exception(“Really bad error!”); try { } catch(FormatException e) { throw e; }