by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers...
Transcript of by Kip Irvineirvinek/cop4814/dropbox/readings/C-sharp.pdf•namespaces •access modifiers...
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
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
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
Copyright Kip Irvine, 2008 4
Non-Java Types
• sbyte (like Java's byte)
• byte – unsigned
• uint
• ulong
• ushort
• decimal
Copyright Kip Irvine, 2008 5
Constants
• compile-time constant: const keyword const int COUNT = 10;
• run-time constant: readonly keyword readonly double area = getArea();
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")
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
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);
Copyright Kip Irvine, 2008 9
Strings
• immutable, as in Java
• 16-bit Unicode chars
• System.String class
• string type
• For mutable strings, use StringBuilder
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";
Copyright Kip Irvine, 2008 11
ToString( )
• Requires the override keyword
public override string ToString( )
{
string val = "...."
...
return val;
}
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 )
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( );
}
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
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
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
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 {
...
}
}
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,...)
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
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;
}
}
Copyright Kip Irvine, 2008 21
Properties
• New feature: automatic properties
class Student {
public int Id { get; set; }
}
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;
}
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};
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 + ", " );
}
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;
}
Copyright Kip Irvine, 2008 26
Extending Classes
• The : operator means extends
class Employee : Person {
}
• Cannot extend a sealed class:
public sealed class MyClass {
}
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.
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(); }
}
Copyright Kip Irvine, 2008 29
System.Collections Namespace
• Classes
• ArrayList
• Stack
• Queue
• HashTable
• SortedList
• Interfaces
• ICollection
• IComparer
• IDictionary
• IDictionaryEnumerator
• IEnumerable
• IEnumerator
• IEqualityComparer
• IHashCodeProvider
• IList
Copyright Kip Irvine, 2008 30
The End