chapter i c#(console application and programming)

Post on 14-Apr-2017

297 Views

Category:

Education

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Console Application

1. C# code that compiles into CIL2. compiled together into a single assembly3. compiled into native code using a JIT compiler4. native code is executed in the context of the managed CLR.

Characteristic of C#• evolution of the C and C++ languages• OOP/Document Object• C# is case sensitive• designed to incorporate many of the best features from

other languages.• Applications You Can Write with C#– Windows applications– Web applications– Web services– Console applications– Mobile Application

WHAT YOU LEARNED• Console applications: are simple command-line

applications Create a new console application with the Console Application template that you see when you create a new project in VS or VCE. To run a project in debug mode, use the Debug Start Debugging menu item, or press F5.➪

• Windows Forms applications: Windows Forms applications are applications that have the look and feel of standard desktop applications, including the familiar icons to maximize, minimize, and close an application. They are created with the Windows Forms template in the New Project dialog box.

• 4 primary elements, a namespace declaration, a class, a Main method, and a program statement. csc.exe <=(compile)Welcome.cs

• using statements let you reference a namespace and allow code to have shorter and more readable notation

• The Main method is the entry point to start a C# program • Namespaces are also used as a means of categorizing items in the .NET Framework.

Comment

• ignored by the compiler but are very useful for developers because they help document what a program is actually doing.– /* This is a comment */– /* And so...

... is this! */– // This is a different sort of comment.– /// A special comment

• Console.WriteLine("The first app in Beginning C# Programming!");• Console.ReadKey();

• Console.Write("What is your name?: ");• Console.Write("Hello, {0}! ", Console.ReadLine());• Console.WriteLine("Welcome to the C# Station Tutorial!");• Console.ReadLine();

Variables and Types

• variables are concerned with the storage of data.• Storage locations for data • interpretation of the data in a variable is

controlled through "Types". – Boolean Type: true/false 1/0– Numeric type

• Integrals• Floating Point

– float and double types • Decimal

– String

The Boolean Type

• 0 false, else trueusing System;

class Booleans{ public static void Main() { bool content = true; bool noContent = false;

System.Console.WriteLine("It is {1} that {0} C# Station provides C# programming language content.", content,v2); Console.WriteLine("The statement above is not {0}.", noContent); }}

Integral Types

Floating Point and Decimal Types

The string Type• A string is a sequence of text characters

Literal Values

Character Escape Sequences

EXPRESSIONS

Operators can be roughly classified into three categories: ➤ Unary— Act on single operands ➤ Binary—Act on two operands ➤ Ternary—Act on three operands

static void Main(string[] args){Console.WriteLine("Enter an integer:");int myInt = Convert.ToInt32(Console.ReadLine());bool isLessThan10 = myInt < 10;bool isBetween0And5 = (0 <= myInt) && (myInt <= 5);Console.WriteLine("Integer less than 10? {0}", isLessThan10);Console.WriteLine("Integer between 0 and 5? {0}", isBetween0And5);Console.WriteLine("Exactly one of the above is true? {0}",isLessThan10 ˆ isBetween0And5);Console.ReadKey();}Code

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { double firstNumber, secondNumber; string userName; Console.WriteLine("Enter your name:"); userName = Console.ReadLine(); Console.WriteLine("Welcome {0}!", userName); Console.WriteLine("Now give me a number:"); firstNumber = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Now give me another number:"); secondNumber = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("The sum of {0} and {1} is {2}.", firstNumber,secondNumber, firstNumber + secondNumber); Console.WriteLine("The result of subtracting {0} from {1} is {2}.",secondNumber, firstNumber, firstNumber - secondNumber); Console.WriteLine("The product of {0} and {1} is {2}.", firstNumber,secondNumber, firstNumber * secondNumber); Console.WriteLine("The result of dividing {0} by {1} is {2}.",firstNumber, secondNumber, firstNumber / secondNumber); Console.WriteLine("The remainder after dividing {0} by {1} is {2}.",firstNumber, secondNumber, firstNumber % secondNumber); Console.ReadKey(); } }}

THE GOTO STATEMENT• goto labelName;

labelName:Ex:int myInteger = 5;goto myLabel;myInteger += 10;myLabel:Console.WriteLine("myInteger = {0}", myInteger);Ex2:

back: Console.Write("Exit ?(y/n):"); String st = Console.ReadLine(); if (st=="n") goto back;

BRANCHING• The act of controlling which line of code

should be executed next.– The ternary operator– The if statement– The switch statement

The ternary operator

• perform a comparison • <test> ? <resultIfTrue>: <resultIfFalse>• Ex

string resultString = (myInteger < 10) ? "Less than 10”: "Greater than /equal to 10";

The if Statement• if (<test>)

<code executed if <test> is true>;• if (<test>)

<code executed if <test> is true>;else<code executed if <test> is false>;

• Exstatic void Main(string[] args){string comparison;Console.WriteLine("Enter a number:");double var1 = Convert.ToDouble(Console.ReadLine());Console.WriteLine("Enter another number:");double var2 = Convert.ToDouble(Console.ReadLine());if (var1 < var2)comparison = "less than";else{if (var1 == var2)comparison = "equal to";elsecomparison = "greater than";}Console.WriteLine("The first number is {0} the second number.",comparison);Console.ReadKey();}

if (<test>)<code executed if <test> is true>;

Else if(<test>)<code executed if <test> is false>;

…….Else

<code execute>

The switch Statement• Similar to if statement in that it executes code conditionally based on the value of a test.

switch (<testVar: bool, string, int , enum>){case <comparisonVal1>:<code to execute if <testVar>==<comparisonVal1>>

case <comparisonVal2>:<code to execute if <testVar>==<comparisonVal2>>break;...case <comparisonValN>:<code to execute if <testVar>==<comparisonValN>>break;default:<code to execute if <testVar>!= comparisonVals>break;}

Note:Must assign them values: const int intTwo = 2;

LOOPING• repeated execution of statements.

– do Loops• Do {<code to be looped>} while (<Test>);static void Main(string[] args){double balance, interestRate, targetBalance;Console.WriteLine("What is your current balance?");balance = Convert.ToDouble(Console.ReadLine());Console.WriteLine("What is your current annual interest rate (in %)?");interestRate = 1 + Convert.ToDouble(Console.ReadLine()) / 100.0;Console.WriteLine("What balance would you like to have?");targetBalance = Convert.ToDouble(Console.ReadLine());int totalYears = 0;do{balance *= interestRate;++totalYears;}while (balance < targetBalance);Console.WriteLine("In {0} year{1} you’ll have a balance of {2}.",totalYears, totalYears == 1 ? "": "s", balance);Console.ReadKey();}

• While Loopwhile (<condition>){<code to loop><operation>}

• For Loopsfor (<initialization>; <condition>;<operation>){<code to loop>}

static void Main(string[] args){double realCoord, imagCoord;double realTemp, imagTemp, realTemp2, arg;int iterations;for (imagCoord = 1.2; imagCoord >= -1.2; imagCoord -= 0.05){for (realCoord = -0.6; realCoord <= 1.77; realCoord += 0.03){iterations = 0;realTemp = realCoord;imagTemp = imagCoord;arg = (realCoord * realCoord) + (imagCoord * imagCoord);while ((arg < 4) && (iterations < 40)){realTemp2 = (realTemp * realTemp)-(imagTemp * imagTemp)-realCoord;imagTemp = (2 * realTemp * imagTemp) -imagCoord;realTemp = realTemp2;arg = (realTemp * realTemp) + (imagTemp * imagTemp);iterations += 1;}

switch (iterations % 4){case 0:Console.Write(".");break;case 1:Console.Write("o");break;case 2:Console.Write("O");break;case 3:Console.Write("@");break;}}Console.Write("\n");}Console.ReadKey();}

TYPE CONVERSION• Implicit conversion: Conversion from type A to type B is

possible in all circumstances.ushort destinationVar;char sourceVar = ‘a’;destinationVar = sourceVar;Console.WriteLine("sourceVar val: {0}", sourceVar);Console.WriteLine("destinationVar val: {0}", destinationVar);

• Explicit conversion: Conversion from type A to type B is possible only in certain circumstances.

Implicit conversion

Explicit ConversionsEX0:(Error)byte destinationVar;short sourceVar = 7;destinationVar = sourceVar;Console.WriteLine("sourceVar val: {0}", sourceVar);Console.WriteLine("destinationVar val: {0}", destinationVar);EX1:byte destinationVar;short sourceVar = 7;destinationVar = (byte)sourceVar;Console.WriteLine("sourceVar val: {0}", sourceVar);Console.WriteLine("destinationVar val: {0}", destinationVar);EX2:byte destinationVar;short sourceVar = 281;destinationVar = (byte)sourceVar;Console.WriteLine("sourceVar val: {0}", sourceVar);Console.WriteLine("destinationVar val: {0}", destinationVar);

Explicit Conversions Using the Convert Commands

static void Main(string[] args){

short shortResult, shortVal = 4;int integerVal = 67;long longResult;float floatVal = 10.5F;double doubleResult, doubleVal = 99.999;string stringResult, stringVal = "17";bool boolVal = true;

Console.WriteLine("Variable Conversion Examples\n");doubleResult = floatVal * shortVal;

Console.WriteLine("Implicit, -> double: {0} * {1} -> {2}", floatVal,shortVal,doubleResult);

shortResult = (short)floatVal;Console.WriteLine("Explicit, -> short: {0} -> {1}", floatVal,shortResult);

stringResult = Convert.ToString(boolVal) +Convert.ToString(doubleVal);Console.WriteLine("Explicit, -> string: \"{0}\" + \"{1}\" -> {2}",boolVal, doubleVal,stringResult);longResult = integerVal + Convert.ToInt64(stringVal);Console.WriteLine("Mixed, -> long: {0} + {1} -> {2}",integerVal, stringVal, longResult);Console.ReadKey();}

COMPLEX VARIABLE TYPES• Enumerations (often referred to as enums)• Structs (occasionally referred to as structures)• Arrays.

Enumerations• Is a data type that enumerates a set of items by assigning to each

of them an identifier (a name), while exposing an underlying base type for ordering the elements of the enumeration.

Step1:enum <typeName> : <underlyingType>{<value1> = <actualVal1>,<value2> = <actualVal2>,<value3> = <actualVal3>,...<valueN> = <actualValN>}

Step2:<typeName> <varName>; <varName> = <typeName>.<value>;

• Note: underlying type: byte, sbyte, short, ushort, int, uint, long, ulong.

EX0:enum CardSuit : byte { Hearts, Diamonds, Spades, Clubs };CardSuit c1 = CardSuit.Hearts;Console.Write(Convert.ToInt16(c1));EX1:enum Weekday { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };Weekday day = Weekday.Monday;if (day == Weekday.Tuesday){ Console.WriteLine("Time sure flies by when you program in C#!");}EX2: enum orientation : byte { north = 1, south = 2, east = 3, west = 4 } class Program { static void Main(string[] args) { orientation myDirection = orientation.north; Console.WriteLine("myDirection = {0}", myDirection); Console.ReadKey(); } }

Structs• Are data structures are composed of several pieces of data, possibly

of different types.• Enable you to define your own types of variables based on this

structure.struct <typeName>{<memberDeclarations>}<accessibility> <type> <name>;

struct Student { public int stuID; public string stuName; public string sex; public string address; public string phone; } class Program { static void Main(string[] args) { Student st1; st1.stuID = 1; st1.stuName = "Sopheap"; st1.sex = "Female"; st1.address = "Siem Reap"; st1.phone = "012 22 33 44"; Student st2; st2.stuID = 2; st2.stuName = "CR"; st2.sex = "Male"; st2.address = "Siem Reap"; st2.phone = "011 11 33 44";Console.WriteLine(st1.stuID + "\t" + st1.stuName + "\t" + st1.sex + "\t" + st1.address + "\t" + st1.phone); Console.WriteLine(st2.stuID + "\t" + st2.stuName + "\t" + st2.sex + "\t" + st2.address + "\t" + st2.phone); Console.ReadKey(); }}

enum orientation: byte{north = 1,south = 2,east = 3,west = 4}struct route{public orientation direction;public double distance;}

class Program{static void Main(string[] args){route myRoute;int myDirection = -1;double myDistance;Console.WriteLine("1) North\n2) South\n3) East\n4) West");do{Console.WriteLine("Select a direction:");myDirection = Convert.ToInt32(Console.ReadLine());}while ((myDirection < 1) || (myDirection > 4));Console.WriteLine("Input a distance:");myDistance = Convert.ToDouble(Console.ReadLine());myRoute.direction = (orientation)myDirection;myRoute.distance = myDistance;Console.WriteLine("myRoute specifies a direction of {0} and a " +"distance of {1}", myRoute.direction, myRoute.distance);Console.ReadKey();}}

Declaring Arrays• An array is a special type of variable—it's a variable with

multiple dimensions.• Want to store several values of the same type at the same

time, without having to use a different variable for each value.

• Specifying an array using literal values– int[] myIntArray = { 34, 65, 10, 2, 99};

• The other method requires the following syntax:– int[] myIntArray = new int[arraySize];

• combine these two methods of initialization– const int arraySize = 5;– int[] myIntArray = new int[arraySize] { 5, 9, 10, 2, 99 };

Declaring Arraysstring[] strMyArray;strMyArray = new string[10];

object[] objPersonalInfo;objPersonalInfo = new object[10];objPersonalInfo[0] = "James Foxall";objPersonalInfo[1] = "Papillion";objPersonalInfo[2] = "Nebraska";objPersonalInfo[3] = 32;

EX1:static void Main(string[] args){

string[] friendNames = { "Robert Barwell", "Mike Parry","Jeremy Beacock" };int i;Console.WriteLine("Here are {0} of my friends:",friendNames.Length);for (i = 0; i < friendNames.Length; i++){

Console.WriteLine(friendNames[i]);}Console.ReadKey();}

Note:foreach Loopsforeach (<baseType> <name> in <array>){// can use <name> for each element}

static void Main(string[] args){string[] friendNames = { "Robert Barwell", "Mike Parry","Jeremy Beacock" };Console.WriteLine("Here are {0} of my friends:",friendNames.Length);foreach (string friendName in friendNames){Console.WriteLine(friendName);}Console.ReadKey();}

Multidimensional Arrays• is simply one that uses multiple indices to access its

elements.– A two-dimensional array

• <baseType>[,] <name>;– Arrays of more dimensions

• <baseType>[,,,] <name>;– EX

• double[,] hillHeight = new double[3,4];• double[,] hillHeight = { { 1, 2, 3, 4 }, { 2, 3, 4, 5 }, { 3, 4, 5, 6 } };• hillHeight[2,1]

int[ ,] intMeasurements;intMeasurements = new int[3,2];

EX1:double[,] hillHeight = { { 1, 2, 3, 4 }, { 2, 3, 4, 5 }, { 3, 4, 5, 6 } };foreach (double height in hillHeight){Console.WriteLine("{0}", height);}EX2:

Arrays of Arrays• int[][] jaggedIntArray;• jaggedIntArray = new int[3][4];• jaggedIntArray = { { 1, 2, 3 }, { 1 }, { 1, 2 } };• jaggedIntArray = new int[3][] { new int[] { 1, 2, 3 }, new int[] { 1 },new int[] { 1, 2 } };• int[][] jaggedIntArray = { new int[] { 1, 2, 3 }, new int[] { 1 },new int[] { 1, 2 } };• int[][] divisors1To10 = { new int[] { 1 },new int[] { 1, 2 },new int[] { 1, 3 },

new int[] { 1, 2, 4 },new int[] { 1, 5 },new int[] { 1, 2, 3, 6 },new int[] { 1, 7 },new int[] { 1, 2, 4, 8 },new int[] { 1, 3, 9 },new int[] { 1, 2, 5, 10 } };foreach (int[] divisorsOfInt in divisors1To10){foreach(int divisor in divisorsOfInt){Console.WriteLine(divisor);}}

STRING MANIPULATION• myString.Length• <string>.ToLower()• <string>.ToUpper()• userResponse.Trim()• <string>.TrimStart()• <string>.TrimEnd()• <string>.PadLeft()• <string>.PadRight()• myString.Split(separator)

Functions(methods)• Means of providing blocks of code that can be executed at any point in an application.• have the advantage of making your code more readable, as you can use them to group

related code together.1. None Return Value

static <void> <FunctionName>(){...}

2. Return Values– value exactly the same way that variables evaluate to the values they

contain when you use them in expressions.static <returnType> <FunctionName>(){...return <returnValue>;}

EX1: class Program { static void Write() { Console.WriteLine("Text output from function."); } static void Main(string[] args) { Write(); Console.ReadKey(); } }EX2:class Program{static int MaxValue(int[] intArray){int maxVal = intArray[0];for (int i = 1; i < intArray.Length; i++){if (intArray[i] > maxVal)maxVal = intArray[i];}return maxVal;}

static void Main(string[] args){int[] myArray = { 1, 8, 3, 6, 2, 5, 9, 3, 0, 2 };int maxVal = MaxValue(myArray);Console.WriteLine("The maximum value in myArray is {0}", maxVal);Console.ReadKey();}}

EX3:static int MaxValue(int[] intArray){int maxVal = intArray[0];for (int i = 1; i < intArray.Length; i++){if (intArray[i] > maxVal)maxVal = intArray[i];}return maxVal;}static void Main(string[] args){double[] myArray = { 1.3, 8.9, 3.3, 6.5, 2.7, 5.3 };double maxVal = MaxValue(myArray);Console.WriteLine("The maximum value in myArray is {0}", maxVal);Console.ReadKey();}

Reference and Value Parameters• Any changes made to this variable in the function have no effect on the

parameter specified in the function consider a function that doubles and displays the value of a passed parameter.– EX:

static void ShowDouble(int val){val *= 2;Console.WriteLine("val doubled = {0}", val);}int myNumber = 5;Console.WriteLine("myNumber = {0}", myNumber);ShowDouble(myNumber);Console.WriteLine("myNumber = {0}", myNumber);

//then the text output to the console is as follows:myNumber = 5val doubled = 10myNumber =5

• to pass the parameter by reference, which means that the function will work with exactly the same variable as the one used in the function call, not just a variable that has the same value.– EX:

static void ShowDouble(ref int val){val *= 2;Console.WriteLine("val doubled = {0}", val);}int myNumber = 5;Console.WriteLine("myNumber = {0}", myNumber);

}ShowDouble(ref myNumber);Console.WriteLine("myNumber = {0}", myNumber);//The text output to the console is now as follows:myNumber = 5val doubled = 10myNumber = 10

OVERLOADING FUNCTIONS• capability to create multiple functions with the same name,

but each working with different parameter types.– EX:static void ShowDouble(ref int val){...}static void ShowDouble(int val){...}ShowDouble(ref val);//This would call the value version:ShowDouble(val);

DELEGATES• A delegate is a type that enables you to store

references to functions,

class Program{delegate double ProcessDelegate(double param1, double param2);static double Multiply(double param1, double param2){return param1 * param2;}static double Divide(double param1, double param2){return param1 / param2;}static void Main(string[] args){ProcessDelegate process;Console.WriteLine("Enter 2 numbers separated with a comma:");string input = Console.ReadLine();int commaPos = input.IndexOf(’,’);double param1 = Convert.ToDouble(input.Substring(0, commaPos));double param2 = Convert.ToDouble(input.Substring(commaPos + 1,input.Length - commaPos - 1));Console.WriteLine("Enter M to multiply or D to divide:");input = Console.ReadLine();if (input == "M")process = new ProcessDelegate(Multiply);elseprocess = new ProcessDelegate(Divide);Console.WriteLine("Result: {0}", process(param1, param2));Console.ReadKey();}}

Error Handling• An exception handling statement can be used to handle exceptions

using keywords such as throw, try-catch, try-finally, and try-catch-finally.

• Is an error generated either in your code or in a function called by your code that occurs at runtime.

EX1:long lngNumerator = 10; long lngDenominator = 0; long lngResult; try { Console.WriteLine("Try"); lngResult = lngNumerator / lngDenominator; } catch { Console.WriteLine("Catch"); } finally { Console.WriteLine("Finally"); } Console.WriteLine("Done Trying"); Console.ReadKey();

Dealing with an Exceptioncatch ( Exception variablename)Modify your catch section to match the following:catch (Exception objException){Console.WriteLine ("An error has occurred: " +objException.Message);}

try // Line 63{

Console.WriteLine("ThrowException(\"nested index\") " +"try block reached.");Console.WriteLine("ThrowException(\"index\") called.");Throw new System.ArgumentException(“Message”);}

catch // Line 70{

Console.WriteLine("ThrowException(\"nested index\") general“ + " catch block reached.");}finally{

Console.WriteLine("ThrowException(\"nested index\") finally“ + " block reached.");}

static string[] eTypes = { "none", "simple", "index", "nested index" };static void Main(string[] args){

foreach (string eType in eTypes){

try{Console.WriteLine("Main() try block reached."); // Line 23Console.WriteLine("ThrowException(\"{0}\") called.", eType);// Line 24ThrowException(eType);Console.WriteLine("Main() try block continues."); // Line 26}catch (System.IndexOutOfRangeException e) // Line 28{Console.WriteLine("Main() System.IndexOutOfRangeException catch"+ " block reached. Message:\n\"{0}\"",e.Message);}catch // Line 34{Console.WriteLine("Main() general catch block reached.");}finally{Console.WriteLine("Main() finally block reached.");}Console.WriteLine();

}Console.ReadKey();

}

EX:try{Console.WriteLine("ThrowException(\"nested index\") " +"try block reached.");Console.WriteLine("ThrowException(\"index\") called.");ThrowException("index");}catch{Console.WriteLine("ThrowException(\"nested index\") general“ + " catch block reached.");throw;}finally{Console.WriteLine("ThrowException(\"nested index\") finally"+ " block reached.");}

top related