Difference between revisions of "OOP Class3"

esse quam videri
Jump to: navigation, search
m (Text replacement - "<csharp>" to "<syntaxhighlight lang="csharp" line="1" >")
m (Text replacement - "</csharp>" to "</syntaxhighlight>")
Line 14: Line 14:
 
int Number3 = Number1 / Number2;
 
int Number3 = Number1 / Number2;
 
//Number3 == 1 NOT  1.2 because Number3 is an int
 
//Number3 == 1 NOT  1.2 because Number3 is an int
</csharp>
+
</syntaxhighlight>
  
 
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class2/implicitConversion.cs implicitConversion.cs]
 
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class2/implicitConversion.cs implicitConversion.cs]
Line 27: Line 27:
 
int Number2= 5;
 
int Number2= 5;
 
double Number3 = (double)Number1 / (double)Number2;
 
double Number3 = (double)Number1 / (double)Number2;
//Number3 == 1.2</csharp>
+
//Number3 == 1.2</syntaxhighlight>
  
 
[http://iam.colum.edu/poop/gbrowser.php?file=/classsource/class2/explicitConversion.cs explicitConversion.cs]
 
[http://iam.colum.edu/poop/gbrowser.php?file=/classsource/class2/explicitConversion.cs explicitConversion.cs]
Line 44: Line 44:
  
 
<syntaxhighlight lang="csharp" line="1" >int myVar; //declare varible of type int called myVar
 
<syntaxhighlight lang="csharp" line="1" >int myVar; //declare varible of type int called myVar
myVar = 15;  //assign myVar the value of 15 using the '=' sign</csharp>
+
myVar = 15;  //assign myVar the value of 15 using the '=' sign</syntaxhighlight>
  
 
==Comparison Operators==
 
==Comparison Operators==
Line 123: Line 123:
 
else {
 
else {
 
     // statements
 
     // statements
}</csharp>
+
}</syntaxhighlight>
  
  
Line 173: Line 173:
 
             Console.WriteLine("Your number {0} is not between 1 and 3.", myInt);
 
             Console.WriteLine("Your number {0} is not between 1 and 3.", myInt);
 
             break;
 
             break;
}</csharp>
+
}</syntaxhighlight>
  
 
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class3/Switch1to3.cs Switch1to3.cs]<br />
 
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class3/Switch1to3.cs Switch1to3.cs]<br />
Line 196: Line 196:
 
             Console.WriteLine("Please vote....");
 
             Console.WriteLine("Please vote....");
 
             break;
 
             break;
}</csharp>
+
}</syntaxhighlight>
  
 
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class3/SwitchPolitics.cs SwitchPolitics.cs]<br />
 
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class3/SwitchPolitics.cs SwitchPolitics.cs]<br />
Line 210: Line 210:
 
{
 
{
 
     forOneResult += "For Loop " + i + "<br />";
 
     forOneResult += "For Loop " + i + "<br />";
}</csharp>
+
}</syntaxhighlight>
  
 
Produces
 
Produces
Line 234: Line 234:
  
 
     forTwoResult += "For Loop " + i + "<br />";
 
     forTwoResult += "For Loop " + i + "<br />";
}</csharp>
+
}</syntaxhighlight>
  
 
Produces
 
Produces
Line 261: Line 261:
 
     Whileloopresult +="While Loop " + MyInt + "\n";
 
     Whileloopresult +="While Loop " + MyInt + "\n";
 
     MyInt++;
 
     MyInt++;
}</csharp>
+
}</syntaxhighlight>
  
 
produces
 
produces
Line 290: Line 290:
 
     doLoopResult +="do Loop " + myIntDo + "\n";
 
     doLoopResult +="do Loop " + myIntDo + "\n";
 
     myIntDo++;
 
     myIntDo++;
}      while (myIntDo < 10);</csharp>
+
}      while (myIntDo < 10);</syntaxhighlight>
  
 
produces
 
produces
Line 314: Line 314:
 
         doLoopResult2 +="do Loop " + myInt + "\n";
 
         doLoopResult2 +="do Loop " + myInt + "\n";
 
         myIntDo2++;
 
         myIntDo2++;
} while (myIntDo2 < 10);</csharp>
+
} while (myIntDo2 < 10);</syntaxhighlight>
  
 
produces
 
produces
Line 326: Line 326:
 
{
 
{
 
     Console.Write (" " + person);
 
     Console.Write (" " + person);
}</csharp>
+
}</syntaxhighlight>
  
 
produces<br>
 
produces<br>
Line 383: Line 383:
 
     }
 
     }
 
}
 
}
</csharp>
+
</syntaxhighlight>
  
 
if you type 'monkey' for your favorite number the program crashes with the folling message
 
if you type 'monkey' for your favorite number the program crashes with the folling message
Line 405: Line 405:
 
{
 
{
 
     string FstrError = e.ToString();
 
     string FstrError = e.ToString();
}</csharp>
+
}</syntaxhighlight>
 
 
  
Line 433: Line 433:
 
         }
 
         }
 
     }
 
     }
}</csharp>
+
}</syntaxhighlight>
 
<pre>
 
<pre>
 
C:\User\csharp>csc try.cs
 
C:\User\csharp>csc try.cs
Line 480: Line 480:
 
{
 
{
 
     return "Hello " + Name;
 
     return "Hello " + Name;
}</csharp>
+
}</syntaxhighlight>
  
 
Calling a finction in c#
 
Calling a finction in c#
Line 487: Line 487:
 
firstHello = Hello();  //call the function Hello
 
firstHello = Hello();  //call the function Hello
 
jeffHello = HelloToName("Jeff");  //call the function HelloToName
 
jeffHello = HelloToName("Jeff");  //call the function HelloToName
</csharp>
+
</syntaxhighlight>
  
 
Console Example
 
Console Example
Line 555: Line 555:
 
  public string weight;
 
  public string weight;
 
  public int age;
 
  public int age;
}</csharp>
+
}</syntaxhighlight>
  
 
==Enumerators==
 
==Enumerators==
Line 572: Line 572:
 
   Large = 2,
 
   Large = 2,
 
   SuperSize = 3
 
   SuperSize = 3
}</csharp>
+
}</syntaxhighlight>
 
    
 
    
 
<syntaxhighlight lang="csharp" line="1" >//another more useful example
 
<syntaxhighlight lang="csharp" line="1" >//another more useful example
Line 581: Line 581:
 
     January = 1, February , March, April ,
 
     January = 1, February , March, April ,
 
     May , June , July , August , Sept , Oct , Nov , Dec  
 
     May , June , July , August , Sept , Oct , Nov , Dec  
   }</csharp>
+
   }</syntaxhighlight>
  
 
Enumerator Example [http://iam.colum.edu/Poop/gbrowser.php?file=/classsource/class2/Enum.cs Enum.cs]
 
Enumerator Example [http://iam.colum.edu/Poop/gbrowser.php?file=/classsource/class2/Enum.cs Enum.cs]

Revision as of 18:28, 25 January 2016


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

1 int intNumber = 1000;
2 long lngNumber;
3 lngNumber  = intNumber;
4          
5 int Number1= 6;
6 int Number2= 5;
7 int Number3 = Number1 / Number2;
8 //Number3 == 1	NOT  1.2 because Number3 is an int

implicitConversion.cs

explicit conversion

1 long lngNumber = 1000;
2 int intNumber;
3 intNumber = (int)lngNumber;
4 
5 int Number1= 6;
6 int Number2= 5;
7 double Number3 = (double)Number1 / (double)Number2;
8 //Number3 == 1.2

explicitConversion.cs

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

Operators

ECMA-334 Operators and punctuators


Assignment

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

1 int myVar; //declare varible of type int called myVar
2 myVar = 15;   //assign myVar the value of 15 using the '=' sign

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

Branching

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

  • if
  • switch

Looping

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

Branching Statements

if

syntax

 1 if (expression)
 2     // statement
 3     
 4 if (expression) {
 5     // statements
 6     // statements
 7 }
 8 if (expression) {
 9     // statements
10     // statements
11 }
12 else {
13     // statements
14 }


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.
EchoOnce.cs
Another popular way to get data into your program is to send it in as an argument when the program is run.
HelloName.cs
HelloNameSafe.cs

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

syntax

switch (expression)

{
   case constant-expression:
           statement
           jump-statement
   [default: statement]
}

example 1

 1 // switch with integer type
 2 switch (myInt)
 3 {
 4     case 1:
 5             Console.WriteLine("Your number is {0}.", myInt);
 6             break;
 7     case 2:
 8             Console.WriteLine("Your number is {0}.", myInt);
 9             break;
10     case 3:
11             Console.WriteLine("Your number is {0}.", myInt);
12             break;
13     default:
14             Console.WriteLine("Your number {0} is not between 1 and 3.", myInt);
15             break;
16 }

Switch1to3.cs
Switch1to3WithTryAndCatch.cs

fall though and goto case

 1 // fall though and goto case
 2 switch (myChoice)
 3 {
 4     case "NewLeft":
 5             Console.WriteLine("Newleft is voting Democratic.");
 6             goto case "Democrat";
 7     case "Democrat":
 8             Console.WriteLine("You voted Democratic.");
 9             break;
10     case "CompassionateRepublican":
11     case "Republican":
12             Console.WriteLine("You voted Republican.");
13             break;
14     default:
15             Console.WriteLine("Please vote....");
16             break;
17 }

SwitchPolitics.cs

Looping Statements

for

syntax

    for ([initializers]; [expression]; [iterators]) statement
    
1 for (int i=0; i < 10; i++)
2 {
3     forOneResult += "For Loop " + i + "<br />";
4 }

Produces

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
 1 for (int i=0; i < 20; i++)
 2 {
 3     if (i == 10)
 4             break;
 5 
 6     if (i % 2 == 0)
 7             continue;
 8 
 9     forTwoResult += "For Loop " + i + "<br />";
10 }

Produces

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

while syntax

  while (expression) statement
1 string whileLoopResult = "";
2 int MyInt = 0;
3 
4 while (MyInt < 10)
5 {
6     Whileloopresult +="While Loop " + MyInt + "\n";
7     MyInt++;
8 }

produces

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

do... while syntax

   do statement while (boolean-expression);
   
1 string doLoopResult = "";
2 int myIntDo = 0;
3 
4 do
5 {
6     doLoopResult +="do Loop " + myIntDo + "\n";
7     myIntDo++;
8 }       while (myIntDo < 10);

produces

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


1 string doLoopResult2 = "";
2 int myIntDo2 = 30;
3 
4 do
5 {
6         doLoopResult2 +="do Loop " + myInt + "\n";
7         myIntDo2++;
8 }	while (myIntDo2 < 10);

produces do Loop 30

for each

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

1 string[] names = {"Cheryl", "Joe", "Matt", "Robert"};
2 foreach (string person in names)
3 {
4     Console.Write (" " + person);
5 }

produces

 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.

Generics

  • List
  • Queue
  • Stack
  • .etc

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.

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 
 5 namespace FavoriteNumber
 6 {
 7     class Program
 8     {
 9         static void Main(string[] args)
10         {
11             int intFavNumber;
12             string strFavNumber;
13             
14             Console.Write("What is you favorite number?");
15             strFavNumber = Console.ReadLine();
16 
17             intFavNumber = Int16.Parse(strFavNumber);
18 
19         }
20     }
21 }

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

1 try
2 {
3 	//some crazy code that may cause errors
4 }
5 catch (Exception e)
6 {
7     string FstrError = e.ToString();
8 }


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

 1 using System;
 2 namespace HelloClass
 3 {
 4     class HelloWorld
 5     {
 6         public static void Main()
 7         {
 8             object o2 = null;
 9             try
10             {
11                 int i2 = (int) o2;   // Error
12             }
13             catch (Exception e)
14             {
15                 //put Exceptioninto string strError
16                 string strError = e.ToString();
17                 //write error to label lblOutput
18                 Console.WriteLine(strError);
19             }
20         }
21     }
22 }
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.


C:\User\csharp>try.exe
System.NullReferenceException: Object reference not set to an instance of an obj
ect.
   at HelloClass.HelloWorld.Main()

C:\User\csharp>

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

String Functions in csharp

To Upper method returns a string that only has upper case letters

string strName = "jeff";
Console.WriteLine(strName.ToUpper());

will write JEFF

string strName = "Jeff";
Console.WriteLine(strName.ToLower());

will write jeff

string strName = "jMeyers";
string strNamej = "john jacob jingleheimer Schmidt";

strName = strName .Replace("j" , "J");
strNamej =  strNamej.Replace("j" , "J");

strName will be "JMeyers" strName will be "John Jacob Jingleheimer Schmidt"


etc

Make Our Own String function

protected static void WriteColorFull(string s)
        {
            //Save current console color so we can restore it when we are done
            //We don't want to leave the console with a random color
            ConsoleColor originalConsoleColor = Console.ForegroundColor;

            for (int index = 0; index < s.Length; index++)
            {

                Console.ForegroundColor = mycolors[(mycolors.Length + index) % mycolors.Length];   //Rotate through colors
                Console.Write(s[index]);    //Write the current letter from the string

            }
            Console.Write("\n");

            //Restore Console
            Console.ForegroundColor = originalConsoleColor;

        }

        //An array of console colors
        private static ConsoleColor[] mycolors =
        {
            ConsoleColor.Red,
            ConsoleColor.Magenta,
            ConsoleColor.DarkMagenta,
            ConsoleColor.DarkGreen,
            ConsoleColor.DarkRed,
            ConsoleColor.DarkGray,
            ConsoleColor.DarkBlue,
            ConsoleColor.Blue,
            ConsoleColor.Gray,
            ConsoleColor.Green,
            ConsoleColor.Yellow,
            ConsoleColor.White
        };

Functions/Methods

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

}

access-modifiers
public
private
protected
internal
protected internal
more on these next week.

Defining

1 string Hello ()
2 {
3     return "Hello ";
4 }
5 
6 string HelloToName (string Name)
7 {
8     return "Hello " + Name;
9 }

Calling a finction in c#

1 string firstHello, jeffHello;   //declare some strings
2 firstHello = Hello();   //call the function Hello
3 jeffHello = HelloToName("Jeff");   //call the function HelloToName

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.


C:\User\csharp>function.cs

C:\User\csharp>function.exe
Hello World!
Hello
Hello Jeff
Hello Marge

C:\User\csharp>

function.cs

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

Variables

Scope

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 { }.

Scope.cs



Additional Reading

Structs

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}

1 struct Dog
2 {
3  public string name;
4  public string weight;
5  public int age;
6 }

Enumerators

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

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

1 //An enumerator for ServingSizes at BK
2 enum ServingSizes : uint
3 {
4   Small = 0,
5   Regular = 1,
6   Large = 2,
7   SuperSize = 3
8 }
1 //another more useful example
2 // forced sequence to start  
3 // from 1 instead of 0 (default)
4 enum Months 
5   {
6     January = 1, February , March, April ,
7     May , June , July , August , Sept , Oct , Nov , Dec 
8   }

Enumerator Example Enum.cs

Home work

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.

CoinFilpperFunner.cs


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

Video

This text will be replaced