by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers...

30
COP 4813 Web Application Programming Learning C# (c) 2008 Kip Irvine, all rights reserved. You may modify and copy this slide show for your personal use as long as this copyright statement is included. Revision date: 5/15/2013 by Kip Irvine

Transcript of by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers...

Page 1: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

COP 4813

Web Application Programming

Learning C#

(c) 2008 Kip Irvine, all rights reserved. You may modify and copy this slide show for your personal use as long as this

copyright statement is included.

Revision date: 5/15/2013

by Kip Irvine

Page 2: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 2

Outline

• Java similarities

• non-Java types

• constants

• nullable types

• access modifiers

• strings

• ToString( )

• System.Convert

• dynamic cast

• functions

• namespaces

• access modifiers

• properties

• structs

• declaring arrays

• foreach loops

• switch statement

• using blocks

• extending classes

• implementing interfaces

• reflection

• text files

• System.Collections

keyword difference grid

Page 3: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 3

Java Similarities

• Interfaces, single inheritance

• Immutable strings

• Jagged arrays

• Sealed classes

• Reference semantics for objects

• Value semantics for primitives

• Boxing and unboxing of primitive types

Page 4: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 4

Non-Java Types

• sbyte (like Java's byte)

• byte – unsigned

• uint

• ulong

• ushort

• decimal

Page 5: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 5

Constants

• compile-time constant: const keyword const int COUNT = 10;

• run-time constant: readonly keyword readonly double area = getArea();

Page 6: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 6

DateTime Type

• There is no DateTime literal, as in the #...# format

used by Visual Basic

• Represent a date literal:

Convert.ToDateTime("1/1/1900")

Page 7: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 7

Control Characters

• Embeded in strings: "\n", "\t"

• ControlChars class

• Microsoft.VisualBasic namespace ControlChars.CrLf, ControlChars.Tab,

ControlChars.NewLine, ControlChars.Quote

Page 8: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 8

Nullable Types

• Instance of System.Nullable

• Can represent normal range of values, plus null

• Useful when holding database field values

Nullable<bool> status;

bool? status; // alternate format

status = true;

status = false;

status = null;

if(status.HasValue) {

Console.WriteLine("The status is " + status);

Page 9: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 9

Strings

• immutable, as in Java

• 16-bit Unicode chars

• System.String class

• string type

• For mutable strings, use StringBuilder

Page 10: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 10

Verbatim Strings

• Use the @ prefix to ignore escape sequences

string path = @"c:\windows\system32";

• Alternative: string path = "c:\\windows\\system32";

Page 11: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 11

ToString( )

• Requires the override keyword

public override string ToString( )

{

string val = "...."

...

return val;

}

Page 12: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 12

System.Convert Class

Static methods that convert strings to numeric types:

decimal ToDecimal( String )

float ToSingle( String )

double ToDouble( String )

short ToInt16( String )

long ToInt64( String )

ushort ToUInt16( String )

uint ToUInt32( String )

ulong ToUInt64( String )

Page 13: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 13

Dynamic Cast (as)

• Attempts to cast and returns null if it fails

• Can only be used with objects

void Show( Object obj )

{

Student S = obj as Student;

if( S != null )

S.ShowGrade( );

}

Page 14: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 14

Declaring Functions

• Usually begin with uppercase letter

• Basically same as Java

• default: passed by value

• referenced objects can be modified

• ref: passing by reference

• out: output parameters

Page 15: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 15

ref Parameters

bool GetPayInfo(int empId, ref double payRate,

ref int hoursWorked)

{

payRate = ...

hoursWorked = ...

return true;

}

double pay_rate = 0.0;

int hours_worked = 0;

if( GetPayInfo( 1001, pay_rate, hours_worked ) {

// show the pay data

}

must

initialize

Page 16: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 16

out Parameters

bool GetPayInfo(int empId, out double payRate,

out int hoursWorked)

{

payRate = ...

hoursWorked = ...

return true;

}

double pay_rate;

int hours_worked;

if( GetPayInfo( 1001, pay_rate, hours_worked ) {

// show the pay data

}

no need to

initialize

Page 17: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 17

Namespaces

C# namespace keyword encapsulates classes within {

... }

• no relation to directory structure

namespace ProjectUnitTests {

public class TestOne {

...

}

public class TestTwo {

...

}

}

Page 18: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 18

Importing Namespaces

•using directive imports a namespace using ProjectUnitTests;

// rather than this...

Z = new ProjectUnitTests.LoginTests( );

// ...you can write

Z = new LoginTests( );

• You must also identify the namespace's DLL in the

References section (Solution Explorer window)

• (keeps track of the path, version number,...)

Page 19: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 19

Access Modifiers

• private (default for variables and methods)

• public (visible in all assemblies)

• internal (visible only in same assembly)

• protected (visible to subclasses)

• internal protected (internal OR protected)

public class Student {

private int _id;

internal void calcGrade()

protected void setId()

}

classes are internal by default

Page 20: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 20

Properties

• Used in place of Java get and set methods

class Student {

int _id;

public int Id {

get {

return _id;

}

set {

_id = value;

}

}

Page 21: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 21

Properties

• New feature: automatic properties

class Student {

public int Id { get; set; }

}

Page 22: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 22

Structs

• Use value semantics

• Simple, lightweight

• Fields are usually public

struct Point {

public int X;

public int Y;

public Point( int x, int y ) {

this.X = x;

this.Y = y;

}

Page 23: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 23

Arrays

• Reserve storage int[] values = new int[50];

// calculate size at runtime

int count = getSize();

double[] scores = new double[count];

• Declare & initialize int[] ages = {22, 30, 35, 42, 50};

Page 24: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 24

foreach..in Statement

• Iterate over array or collection

string[] names = {"Bob", "Carol","Ted","Alice"};

foreach( string str in names ) {

Console.WriteLine( str + ", " );

}

Page 25: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 25

switch Statement

• C# supports the use of string literals

• The break statement is required

switch( status )

{

case "G":

txtStatus.Text = "Good";

break;

case "P":

txtStatus.Text = "Poor";

break;

default:

txtStatus.Text = "Unknown";

break;

}

Page 26: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 26

Extending Classes

• The : operator means extends

class Employee : Person {

}

• Cannot extend a sealed class:

public sealed class MyClass {

}

Page 27: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 27

Implementing Interfaces

• Use the : operator

class Student : IComparable, ICloneable {

}

• Extending a class and implementing an interface:

class Student : Person, IComparable {

}

Interfaces can contain events, indexers, methods and properties.

Page 28: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 28

Text Files using System.IO; public class FileIOTest { void ReadWriteFile(){ FileStream inputFile = new FileStream("input.txt", FileMode.Open);

FileStream outputFile = new FileStream("output.txt", FileMode.Open);

StreamReader sr = new StreamReader(inputFile);

StreamWriter sw = new StreamWriter(outputFile); String str;

while((str = sr.ReadLine())!= null) {

sw.Write(str);

} sr.Close(); sw.Close(); }

}

Page 29: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 29

System.Collections Namespace

• Classes

• ArrayList

• Stack

• Queue

• HashTable

• SortedList

• Interfaces

• ICollection

• IComparer

• IDictionary

• IDictionaryEnumerator

• IEnumerable

• IEnumerator

• IEqualityComparer

• IHashCodeProvider

• IList

Page 30: by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers •properties •structs •declaring arrays •foreach loops •switch statement •using

Copyright Kip Irvine, 2008 30

The End