+ All Categories
Home > Documents > C#: Introduction for Developers

C#: Introduction for Developers

Date post: 22-Feb-2016
Category:
Upload: yon
View: 30 times
Download: 0 times
Share this document with a friend
Description:
Neal Stublen [email protected]. C#: Introduction for Developers. C# Data Types. 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 ) - PowerPoint PPT Presentation
49
C#: INTRODUCTION FOR DEVELOPERS Neal Stublen [email protected]
Transcript
Page 1: C#: Introduction for Developers

C#: INTRODUCTION

FOR DEVELOPERS

Neal [email protected]

Page 2: C#: Introduction for Developers

C# Data Types

Page 3: 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.)

Page 4: C#: Introduction for Developers

Declare and Initialize

<type> <variableName>;int index;float interestRate;

<type> <variableName> = <value>;int index = 0;float interestRate = 0.0005;

Page 5: C#: Introduction for Developers

Constants

const <type> <variableName> = <value>;

const decimal PI = 3.1415926535897932384626;

Page 6: C#: Introduction for Developers

Naming Conventions Camel Notation (camel-case)

salesTaxCommon for variables

Pascal Notation (title-case)SalesTaxCommon for type names and constants

C or Python stylesales_tax (variable)SALES_TAX (constant)Not common

Page 7: C#: Introduction for Developers

Arithmetic Operators Addition (+) Subtraction (-) Multiplication (*) Division (/) Modulus (%) Increment (++) Decrement (--)

Page 8: C#: Introduction for Developers

Assignment Operators Assignment (=) Addition (+=) Subtraction (-=) Multiplication (*=) Division (/=) Modulus (%=)

Page 9: C#: Introduction for Developers

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;

Page 10: C#: Introduction for Developers

Type Casting Explicit More precise to less precise int->char, double->float

(<type>) <expression>

double total = 4.56;int avg = (int)(total / 10);decimal decValue = (decimal)avg;

Page 11: C#: Introduction for Developers

What Should Happen?int i = 379;double d = 4.3;byte b = 2;

double d2 = i * d / b;

int i2 = i * d / b;

Page 12: C#: Introduction for Developers

"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);

Page 13: C#: Introduction for Developers

Strings string text = "My name is "; text = text + "Neal" text += " Stublen." double grade = 94; string text = "My grade is " + grade + “.”;

Page 14: C#: Introduction for Developers

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.""";

Page 15: C#: Introduction for Developers

Converting Types <value>.ToString(); <type>.Parse(<string>); Convert.ToBool(<value>); Convert.ToString(<value>); Convert.ToInt32(<value>);

Page 16: C#: Introduction for Developers

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

Page 17: C#: Introduction for Developers

Variable Scope Scope limits access and lifetime Class scope Method scope Block scope No officially "global" scope

Page 18: C#: Introduction for Developers

Enumeration Typeenum StoplightColors{    Red,    Yellow,    Green}

Page 19: C#: Introduction for Developers

Enumeration Typeenum StoplightColors{    Red = 10,    Yellow,    Green}

Page 20: C#: Introduction for Developers

Enumeration Typeenum StoplightColors{    Red = 10,    Yellow = 20,    Green = 30}

Page 21: C#: Introduction for Developers

Enumeration Typeenum StoplightColors{    Red = 10}

string color =

  StoplightColors.Red.ToString();

Page 22: C#: Introduction for Developers

"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;

Page 23: C#: Introduction for Developers

Control Structures Boolean expressions

Evaluate to true or false Conditional statements

Conditional execution Loops

Repeated execution

Page 24: C#: Introduction for Developers

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

Page 25: C#: Introduction for Developers

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()

Page 26: C#: Introduction for Developers

Logical Equivalence DeMorgan's Theorem

!(a && b) is the equivalent of (!a || !b) !(a || b) is the equivalent of (!a && !b)

Page 27: C#: Introduction for Developers

if-else Statementsif (color == SignalColors.Red){    Stop();}else if (color == SignalColors.Yellow){    Evaluate();}else if (color == SignalColors.Green){    Drive();}

Page 28: C#: Introduction for Developers

switch Statementsswitch (color ){case SignalColors.Red:

    {        Stop();        break;    }case SignalColors.Yellow:

    {        Evaluate();        break;    }default:

    {          Drive();

        break;    }}

Page 29: C#: Introduction for Developers

while Statementswhile (!file.Eof){    file.ReadByte();}

char ch;do{    ch = file.ReadChar();} while (ch != 'q');

Page 30: C#: Introduction for Developers

for Statementsint factorial = 1;for (int i = 2; i <= value; ++i){    factorial *= i;}

string digits = ""for (char ch = '9'; ch <= '0'; ch-=1){    digits += ch;}

Page 31: C#: Introduction for Developers

break and continue Statementsstring text = "";for (int i = 0; i < 10; i++){    if (i % 2 == 0)        continue;    if (i > 8)        break;    text += i.ToString();}

Page 32: C#: Introduction for Developers

Caution!int index = 0; while (++index < lastIndex){    TestIndex(index);}

int index = 0; while (index++ < lastIndex){    TestIndex(index);}

Page 33: C#: Introduction for Developers

What About This?for (int i = 0; i < 10; i++){}

for (int i = 0; i < 10; ++i){}

Page 34: C#: Introduction for Developers

Debugging Loops

Page 35: C#: Introduction for Developers

Debugging Summary Stepping through code (over, into, out) Setting breakpoints Conditional breakpoints

Page 36: C#: Introduction for Developers

Class Methodsclass 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;    }}

Page 37: C#: Introduction for Developers

Passing Parameters

Page 38: C#: Introduction for Developers

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

Page 39: C#: Introduction for Developers

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

Page 40: C#: Introduction for Developers

Events and Delegates

Page 41: C#: Introduction for Developers

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

Page 42: C#: Introduction for Developers

Exceptions and Validation

Page 43: C#: Introduction for Developers

ExceptionsException

Format Exception Arithmetic Exception

Format Exception Arithmetic Exception

Page 44: C#: Introduction for Developers

Format Exceptionstring value = “ABCDEF”;int number = Convert.ToInt32(value);

Page 45: C#: Introduction for Developers

Overflow Exceptionchecked{ byte value = 200; value += 200;

int temp = 5000; byte check = (byte)temp;}

Page 46: C#: Introduction for Developers

“Catching” an Exceptiontry{ int dividend = 20; int divisor = 0; int quotient = dividend / divisor; int next = quotient + 1;}catch{}

Page 47: C#: Introduction for Developers

Responding to Exceptions A simple message box:

MessageBox.Show(message, title); Set control focus:

txtNumber.Focus();

Page 48: C#: Introduction for Developers

Catching Multiple Exceptionstry {}catch( FormatException e){}catch(OverflowException e){}catch(Exception e){}finally{}

Page 49: C#: Introduction for Developers

Throwing an Exceptionthrow new Exception(“Really bad error!”);

try{}catch(FormatException e){ throw e;}


Recommended