Difference between revisions of "OOP Class3"

esse quam videri
Jump to: navigation, search
(Home work)
m (Functions/Methods)
Line 453: Line 453:
/infod/jeff/classSource/class2/try.cs - source
/infod/jeff/classSource/class2/try.cs - source
{{Csharp strings}}

Revision as of 20:15, 23 September 2010

Conversion Casting

Casting is the process of converting form one type of object to another, There are two Conversion types in C# implicit and explicit. Implicit conversion is handled by the compiler and requires no extra work. Implicit conversion is only possible if the new data type can hold the old data type with out any data loss. explicit conversion forces on datatype into another even if it doesn't fit. It is up to the programmer to define explicit casts.

implicit conversion

<csharp>int intNumber = 1000; long lngNumber; lngNumber = intNumber;

int Number1= 6; int Number2= 5; int Number3 = Number1 / Number2; //Number3 == 1 NOT 1.2 because Number3 is an int </csharp>


explicit conversion

<csharp>long lngNumber = 1000; int intNumber; intNumber = (int)lngNumber;

int Number1= 6; int Number2= 5; double Number3 = (double)Number1 / (double)Number2; //Number3 == 1.2</csharp>


Some types cannot be cast from one type to another but the Framework has it's ows Conversion Class. Convert

ConvertClass.cs and Emample of using the convert class to convert an interger to a boolean


ECMA-334 Operators and punctuators


The Assigment operator in c# is the '=' sign. You can assign variables like this...

<csharp>int myVar; //declare varible of type int called myVar myVar = 15; //assign myVar the value of 15 using the '=' sign</csharp>

Comparison Operators

Operator Description
== Equality
< Less Than
<= Less than or equal to
> Greater than
>= Greater than or equal to
!= Inequality

Logical Operators

Operator Description
&& Logical AND
II Logical OR (note the II are really pipes)
! Logical NOT

Boolean Expressions

Logical operators usually work on bollean expressions. Boolean expressions are is a statement that evaluates to true of false

(1 < 2)
(y == x)

Boolean expressions are often grouped with logical operator to combine comparisons

(x > 0) && (x <100) //x is greater than 0 and less than 100
(x < 0) || (x >100) //x is less than zero or x is greater than 100

Logical operator Precedence

  1.  ! (NOT)
  2. && (AND)
  3. || (OR)


evil goto - I won't show it figure it out on your own...

  • if
  • switch


  • for
  • while
  • do... while
  • foreach

Branching Statements



<csharp>if (expression)

   // statement

if (expression) {

   // statements
   // statements

} if (expression) {

   // statements
   // statements

} else {

   // statements


About braces and indenting. I usually use BSD/Allman Style.
Jargon File
indent style n.
The One True Brace Style

  Console Input
  There are several ways to get data into your program. One of the simplest is to have someone type it into the console.
  The frame work supports Console.ReadLine() this method reads on line from the input of the console.
Another popular way to get data into your program is to send it in as an argument when the program is run.

if example IfSelection.cs - source

The following code uses a bunch of operator and if statements to do some basic sanity checks. Analyze it and try to predict the output
sanityCheck.cs - source



switch (expression)

   case constant-expression:
   [default: statement]

example 1

<csharp>// switch with integer type switch (myInt) {

   case 1:
           Console.WriteLine("Your number is {0}.", myInt);
   case 2:
           Console.WriteLine("Your number is {0}.", myInt);
   case 3:
           Console.WriteLine("Your number is {0}.", myInt);
           Console.WriteLine("Your number {0} is not between 1 and 3.", myInt);



fall though and goto case

<csharp>// fall though and goto case switch (myChoice) {

   case "NewLeft":
           Console.WriteLine("Newleft is voting Democratic.");
           goto case "Democrat";
   case "Democrat":
           Console.WriteLine("You voted Democratic.");
   case "CompassionateRepublican":
   case "Republican":
           Console.WriteLine("You voted Republican.");
           Console.WriteLine("Please vote....");



Looping Statements



    for ([initializers]; [expression]; [iterators]) statement

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

   forOneResult += "For Loop " + i + "



For Loop 0
For Loop 1
For Loop 2
For Loop 3
For Loop 4
For Loop 5
For Loop 6
For Loop 7
For Loop 8
For Loop 9

<csharp>for (int i=0; i < 20; i++) {

   if (i == 10)
   if (i % 2 == 0)
   forTwoResult += "For Loop " + i + "



For Loop 1
For Loop 3
For Loop 5
For Loop 7
For Loop 9

For loops can also be good to dynamically add or alter the contents or web controls. For example If I wanted a web control to have 100 items in it like this . I could use a for loop to add them here's an example

/infod/jeff/classSource/class3/DynamicAddDropdown.aspx - source


while syntax

  while (expression) statement

<csharp>string whileLoopResult = ""; int MyInt = 0;

while (MyInt < 10) {

   Whileloopresult +="While Loop " + MyInt + "\n";



While Loop 0
While Loop 1
While Loop 2
While Loop 3
While Loop 4
While Loop 5
While Loop 6
While Loop 7
While Loop 8
While Loop 9


do... while syntax

   do statement while (boolean-expression);

<csharp>string doLoopResult = ""; int myIntDo = 0;

do {

   doLoopResult +="do Loop " + myIntDo + "\n";

} while (myIntDo < 10);</csharp>


do Loop 0
do Loop 1
do Loop 2
do Loop 3
do Loop 4
do Loop 5
do Loop 6
do Loop 7
do Loop 8
do Loop 9

<csharp>string doLoopResult2 = ""; int myIntDo2 = 30;

do {

       doLoopResult2 +="do Loop " + myInt + "\n";

} while (myIntDo2 < 10);</csharp>

produces do Loop 30

for each

A for each loop requires and iterator.. more on this iterator thing later...

<csharp>string[] names = {"Cheryl", "Joe", "Matt", "Robert"}; foreach (string person in names) {

   Console.Write (" " + person);



 Cheryl Joe Matt Robert

ForEachLoop.cs - source

The for each loop is a key component in polymorphism. Remember the age selector example what if we want to select more than one age. It would be simple to change the dropdownlist into a listbox and turn SelectionMode ="Multiple" so the user can select multiple items but how do check to see if every Item is selected. Is to have each item check itself and use a for each loop.

http://iam.colum.edu/oop/classSource/class3/old/DynamicAddListBoxPoly.aspx source

How about making those checkboxes?

http://iam.colum.edu/oop/classSource/class3/old/DynamicAddCheckBoxPoly.aspx [1]

Make em horzontal and only 10 long

http://iam.colum.edu/oop/classSource/class3/old/DynamicAddCheckBoxPolyHoriz.aspx [2]

IN Class

Build a c# app that writes the words to 99 bottles of beer on the wall using a loopin statement

99 bottles of beer csharp example

Try and Catch

Try and catch is useful when you are going to do something that may cause a runtime error. These arrroe my occur when

  • Parsing user input
  • Converting Datatypes
  • Trying to connect to a remote server
  • Connecting to a database

For example consider a program that asks the user what their favorite number is.

<csharp> using System; using System.Collections.Generic; using System.Text;

namespace FavoriteNumber {

   class Program
       static void Main(string[] args)
           int intFavNumber;
           string strFavNumber;
           Console.Write("What is you favorite number?");
           strFavNumber = Console.ReadLine();
           intFavNumber = Int16.Parse(strFavNumber);

} </csharp>

if you type 'monkey' for your favorite number the program crashes with the folling message

Unhandled Exception: System.FormatException: Input string was not in a correct format.
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolea
n parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at System.Int16.Parse(String s, NumberStyles style, NumberFormatInfo info)
   at FavoriteNumber.Program.Main(String[] args)

This program can be fixed be using a try and catch

<csharp>try { //some crazy code that may cause errors } catch (Exception e) {

   string FstrError = e.ToString();


Console Example http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class3/try.cs

<csharp>using System; namespace HelloClass {

   class HelloWorld
       public static void Main()
           object o2 = null;
               int i2 = (int) o2;   // Error
           catch (Exception e)
               //put Exceptioninto string strError
               string strError = e.ToString();
               //write error to label lblOutput


C:\User\csharp>csc try.cs
Microsoft (R) Visual C# .NET Compiler version 7.10.3052.4
for Microsoft (R) .NET Framework version 1.1.4322
Copyright (C) Microsoft Corporation 2001-2002. All rights reserved.

System.NullReferenceException: Object reference not set to an instance of an obj
   at HelloClass.HelloWorld.Main()


/infod/jeff/classSource/class2/try.cs - source


Strings are an object in c#

String concatenation

+ is also used to concatenate strings

If you have two string that you want to combine into one string you can concatenate them. Or use the super jedi .net method String.Format method

<csharp>//Create a string and set it's value to "cool." string coolString = "cool"; //Do some concatenations and make it super cool Console.WriteLine ("Super " + "string " + "theory!!!\n" + "Is really " + coolString + ".");

string notherCoolString = "another " + coolString + " string."; Console.WriteLine(notherCoolString);

Console.WriteLine(String.Format("In Line formating of '{0}'", notherCoolString));


will output (remember \n is a new line)

    Super string theory!!!!
    Is really cool.
    another cool string.
    In Line formating of 'another cool string.'

Escape Sequences

The backslash character is used as a string escape sequence. It will escape the next character and change it's meaning. For example \" with output a ", \n with out put a newline and \\ with output a single \.


Function help with code reuse. If your going to use it more than once make it into a funtions. syntax simple

[access-modifier] return type indentifier ( [parateters] ) {

   //some code


protected internal
more on these next week.


<csharp>string Hello () {

   return "Hello ";


string HelloToName (string Name) {

   return "Hello " + Name;


Calling a finction in c#

<csharp>string firstHello, jeffHello; //declare some strings firstHello = Hello(); //call the function Hello jeffHello = HelloToName("Jeff"); //call the function HelloToName </csharp>

Console Example /infod/jeff/classSource/class3/function.cs - source

C:\User\csharp>csc function.cs
Microsoft (R) Visual C# .NET Compiler version 7.10.3052.4
for Microsoft (R) .NET Framework version 1.1.4322
Copyright (C) Microsoft Corporation 2001-2002. All rights reserved.


Hello World!
Hello Jeff
Hello Marge



Passing variable into a function/method passes be instance. Variables passed by instance do not actually pass in the original variable rather a copy or new instance of the variable is passed. It you want to pass in the actual variable you need to pass be referance Examples of passesing by instamce and passing by refecnce... /infod/jeff/classSource/class3/instanceReference.aspx - Source



scope defines the life of a variable. Local Variables

Variables declared with functions/methods are only around as long as the function/method is running. These variables are known as local varables

Global Variables

Global variables are variables that are around for the entire length of execution. They are declared a public within the programs base class.
In c# since everything must be contianed in a class global variables do not really exist.

Block Level Variables

Block level variables exitist with the code block.
A code block is contained by { }.


Additional Reading


Lightweight alternatives to classes. Structs do not support inheritance or destructors. Don't worry if you don't understand structs yet it hard cuz the book teaches them before classes. We will talk more about stucts after we talk about classes Syntax

[ attributes] [access-modifiers] struct identifier [:interface-list {struct members}

<csharp>struct Dog {

public string name;
public string weight;
public int age;



Enumerators are used to set predefined list of named constants. Syntax

[ attributes] [modifiers] enum identifier [:base-type {enumerator-list};

<csharp>//An enumerator for ServingSizes at BK enum ServingSizes : uint {

 Small = 0,
 Regular = 1,
 Large = 2,
 SuperSize = 3


<csharp>//another more useful example // forced sequence to start // from 1 instead of 0 (default) enum Months

   January = 1, February , March, April ,
   May , June , July , August , Sept , Oct , Nov , Dec 

Enumerator Example Enum.cs

Home work

1. Create three more versions of 99 bottles of beer. 3 pts

  • for
  • do
  • while
  • try using a function

99 bottles of beer csharp example

If you have done 99 bottles of beer then do Ten Monkeys http://www-cs.canisius.edu/~hertzm/csc212f06/Homework/week1/monkey.html

extra foreach

2. Read Chapter 6,7 in Learning c#

  • Create a console Game of Chance 2 pts
    • A coinflipper
    • A dice roller
    • Guess My Number

The game should contain some level of randomness. It should also demonstrate operators and branching statements. It would sure be nice if the game had some level input from the user.

Here is an example coin flipper worth 2 pts CoinFilpperSimple.cs

This game flips a whole bunch of coins two and compares the results. If the two coins are the same then you are a winner and it displays true. If they are different then you loose and if displays false. This program was created to test the old question 'If you flip a coins 99 times and get 99 head what are the odds of the 100th flip turning up heads?'

It shows some strange properties of randomness.


Quiz 1 next week over weeks 1-3 and Chapter 1-6 in Learning c#