Difference between revisions of "OOP Class2"

esse quam videri
Jump to: navigation, search
(Declaration)
 
(118 intermediate revisions by 5 users not shown)
Line 1: Line 1:
 +
[[Category:Object Oriented Programming]]
 +
==Posting home work and website==
 +
 +
review Posting homework to moodle
 +
 
=C# fundamentals=
 
=C# fundamentals=
  
Line 8: Line 13:
 
A Comparative Overview of C# http://genamics.com/developer/csharp_comparative.htm
 
A Comparative Overview of C# http://genamics.com/developer/csharp_comparative.htm
  
C# and Java: Comparing Programming Languages http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncenet/html/tchCJavaComparingProgrammingLanguages.asp
+
C# and Java: Comparing Programming Languages http://msdn.microsoft.com/en-us/library/ms836794.aspx
 +
 
 +
==Terms==
 +
 
 +
CLR
 +
:Common Language Runtime https://en.wikipedia.org/wiki/Common_Language_Runtime
 +
namespace
 +
:organizing classes with hierarchy
 +
keyword
 +
:reserved system word
 +
MSIL
 +
:MicroSoft Intermediary Language
 +
JIT
 +
:Just In Time compilation @ first run https://en.wikipedia.org/wiki/Just-in-time_compilation
 +
 
 +
==Everything is an Object==
 +
In c# everything is an object. And all objects inherit from the object class.
 +
 
 +
[http://quickstarts.asp.net/QuickStartv20/util/classbrowser.aspx See object in the classbrowser]
 +
 
 +
Since all objects inherit from the object class they all have some the basic functionality like a method called ToString();
 +
 
 +
[https://github.com/mono/mono/blob/mono-2-0/mcs/class/corlib/System/Object.cs See the source for object.cs from mono]
  
 
==Basic Data Types==
 
==Basic Data Types==
  
C# is a strongly typed language. This means every object in C# must be declared to be of a specific type.
+
C# is a strongly typed language. This means every object in C# must be declared to be of a specific type. All of c# basic varible type inherit from [http://msdn2.microsoft.com/en-us/library/system.object.aspx System.Object]
Variable Types
+
 
{|-
+
{{.NET Data Types}}
|Type
+
 
|Size in Bytes
 
|.Net Type
 
|Description
 
|-
 
| byte || 1 || Byte || Unsigned (0-255)
 
|-
 
| char ||2 || Char ||Unicode Characters ascii unicode and other
 
|-
 
| bool 1 ||Boolean || True of False || (note c# boolean values do not eqaute to interget value True != (read as is not equal to) 1 and False != 0)
 
|-
 
|sbyte || 1 ||SByte ||Signed integers(-128 to 127)
 
|-
 
|short ||2 ||Int16 || Signed integers(-32,768 to 32,767)
 
|-
 
|ushort || 2 ||UInt16 || Unsigned integers(0 to 65,535)
 
|-
 
|int ||4 || Int32 ||Signed integers(-2,147,483,648 to 2,147,483,647)
 
|-
 
|uint || 4 || UInt32 || Unsigned integers(0 to 4,294,967,295)
 
|-
 
|float || 4 ||Single || fixed-precision up to 7 digits. Floating point number ( 1.5 x 10-45 to 3.4 x 1038 )
 
|-
 
|double || 8 ||Double || fixed-precision up to 16 digits. Floating point number ( 5.0 x 10-324 to 1.7 x 10308 )
 
|-
 
|decimal || 12 || Decimal || fixed-precision up to 28 digits. Typically used for financial calculations. Required the suffix "m" or "M"
 
|-
 
|long || 8 || Int64 || Signed integer ( -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)
 
|-
 
|ulong || 8 || UInt64  || Unsigned integer (0 to 18,446,744,073,709,551,615 )
 
|}
 
 
Variables must be declared with an identifier and then initialized.
 
Variables must be declared with an identifier and then initialized.
  
Line 52: Line 49:
 
Declaration sets aside a named section of memory the is the proper size to hold the declared type. At this point the variable contains nothing.
 
Declaration sets aside a named section of memory the is the proper size to hold the declared type. At this point the variable contains nothing.
  
<csharp>// declare a variable
+
<syntaxhighlight lang="csharp">// declare a variable
 
int firstInt; //declares a vaiable of type int
 
int firstInt; //declares a vaiable of type int
string myString;  //declares a vaiable of type string</csharp>
+
string myString;  //declares a vaiable of type string</syntaxhighlight>
  
 
===Initialization===
 
===Initialization===
Line 60: Line 57:
 
Initialization actually sets the variables value
 
Initialization actually sets the variables value
  
// initialize the variable
+
<syntaxhighlight lang="csharp">// initialize the variable
 
firstInt = 1;
 
firstInt = 1;
myString = "Hello!";
+
myString = "Hello!";</syntaxhighlight>
 +
 
 +
Initialization uses the assignment operator to set the value of a variable
 +
 
 +
===Assignment===
 +
The Assignment '''operator''' in c# is the '=' sign. You can assign variables like this...
 +
 
 +
==Assignment==
 +
The Assignment operator in c# is the '=' sign. You can assign variables like this...We'll learn more about operators later.
  
 
other ways to do it
 
other ways to do it
  
// declare some variables
+
<syntaxhighlight lang="csharp">// declare some variables
 
int secondInt, thirdInt, fourthInt;
 
int secondInt, thirdInt, fourthInt;
 
secondInt = 2;
 
secondInt = 2;
Line 73: Line 78:
  
 
//declare and initialize variables in one line
 
//declare and initialize variables in one line
int myNegativeInt = -2147483648;
+
int myNegativeInt = -2147483648;</syntaxhighlight>
  
 
In c# variables cannot be used unil they are initalized.
 
In c# variables cannot be used unil they are initalized.
 
For example
 
For example
  
    int UsedBeforeInit;
+
<syntaxhighlight lang="csharp">int UsedBeforeInit;
    Console.WriteLine(UsedBeforeInit);
+
Console.WriteLine(UsedBeforeInit);</syntaxhighlight>
  
 
will produce
 
will produce
  
helloError4.cs(10,31): error CS0165: Use of unassigned local variable
+
  helloError4.cs(10,31): error CS0165: Use of unassigned local variable 'UsedBeforeInit'
        'UsedBeforeInit'
 
  
UsedBeforeInit.aspx - web example of misused variable source
+
==Variable Names==
UsedBeforeInit_Fixed.aspx - all beter now source
 
  
More examples of built in types
+
Variable should be named with meaningful names.
1x1.cs C# intrinsic types from Learn-C-Sharp.
+
 
variable.aspx - example from book aspx page View Source
+
for exmaple
variable2.aspx = example from book errors View Source
+
:z = x * y;
 +
 
 +
does not convey any meaning
 +
 
 +
but
 +
:distance = speed * time;
 +
 
 +
does convey meaning.
 +
If varibales are named properly it can make your code mush easier to read.
  
 
==Naming conventions==
 
==Naming conventions==
 
Name variables intelligently.
 
Name variables intelligently.
 +
 
Name variables with names that have meaning.
 
Name variables with names that have meaning.
  
Hungarian Notation
+
===Hungarian Notation===
 
Hungarian notation id a popular notation system used be many C, C++ and VB programmers. It was originally devised in Charles Simonyi's doctoral thesis, "Meta-Programming: A Software Production Method." Hungarian notation specifies that a prefix be added to each variable that indicated that variables type. It also specifies sometimes adding a suffice to clarify variables meaning. In the early 1980's Microsoft adopted this notation system.
 
Hungarian notation id a popular notation system used be many C, C++ and VB programmers. It was originally devised in Charles Simonyi's doctoral thesis, "Meta-Programming: A Software Production Method." Hungarian notation specifies that a prefix be added to each variable that indicated that variables type. It also specifies sometimes adding a suffice to clarify variables meaning. In the early 1980's Microsoft adopted this notation system.
  
  
ie... intHitCounter, intHitsPerMonthMax Hungarian Notation - Charles Simonyi Microsoft
+
ie... intHitCounter, intHitsPerMonthMax  
  
PascalNotation
+
[http://msdn.microsoft.com/en-us/library/aa260976(VS.60).aspx Hungarian Notation - Charles Simonyi Microsoft]
Capitalize first Letter and then the first letter on each word. ie... PascalNotation
+
 
 +
http://msdn.microsoft.com/en-us/library/ms229045.aspx
 +
 
 +
'''PascalNotation'''
 +
Capitalize first Letter and then the first letter on each word.
 +
 
 +
ie... PascalNotation, IntVarName
  
 
Use on method names method names.
 
Use on method names method names.
  
camelNotation
+
'''camelNotation'''
 
Lower case first letter and then capitalize the first letter of each word
 
Lower case first letter and then capitalize the first letter of each word
ie... camelNotation
+
 
 +
ie... camelNotation, intVarName
  
 
use for variable names
 
use for variable names
Other Coding Techniques and practices
+
 
Microsoft - Coding Techniques and Programming Practices
+
Other Coding Techniques and practices<br>
IBM Best Practices for Programming in C
+
*[http://msdn.microsoft.com/en-us/library/ms229002.aspx .NET Framework Developer's Guide Guidelines for Names]
GNU Coding Standards
+
*[http://www-106.ibm.com/developerworks/eserver/articles/hook_duttaC.html?ca=dgr-lnxw06BestC IBM Best Practices for Programming in C]
GNU Naming conventions
+
*[http://www.gnu.org/prep/standards/standards.html GNU Coding Standards]
 +
*[http://www.gnu.org/prep/standards/standards.html#Names GNU Naming conventions]
 +
 
 
More Types
 
More Types
 +
 
==Operators==
 
==Operators==
  
Line 169: Line 191:
 
Evaluated First
 
Evaluated First
  
    * ++,--,unary-
+
* ++,--,unary-
    * *,/,%
+
* *,/,%
    * +,-
+
* +,-
  
 
Evaluated Last
 
Evaluated Last
  
    * =,+=,-=,*=,etc
+
* =,+=,-=,*=,etc
  
  
+ is also used to concatenate strings
+
{{csharp strings}}
 +
{{csharp string functions}}
  
   
+
==Short Assignment==
<csharp>//Create a string and set it's value to "cool."
+
  Short in class Assignment
    string coolString = "cool";
+
  In class assignment 10-15 mins
    //Do some concatenations and make it super cool
+
  Build a c# console app (remember to take a top down aproach start small with something you know maybe start with hello world)
    Console.WriteLine ("Super " + "string " + "theory!!!\n" + "Is really " + coolString + ".");</csharp>
+
    * Declare and initialize two integers
   
+
    * Display their values using Console.WriteLine
 +
    * Declare a third integer and initialize it with the sum of the first two integers
 +
    * Output the value of the third integer
  
will output (remember \n is a new line)
 
  
    Super string theory!!!!
+
Top down development with comments [http://iam.colum.edu/oop/classsource/class2/topdown.aspx topdown.aspx]
    Is really cool.
 
  
 +
Fully implemented Console adding program [http://iam.colum.edu/poop/gbrowser.php?file=/classsource/class2/add.cs add.cs]
  
 +
<syntaxhighlight lang="csharp">
 +
using System;
 +
using System.Collections.Generic;
 +
using System.Text;
  
Short in class Assignment
+
namespace Hello
In class assignment 10-15 mins
+
{
Build a c# console app (remember to take a takedown aproach start small with somethin you know)
+
    class Program
 +
    {
 +
        static void Main(string[] args)
 +
        {
 +
            Console.WriteLine("Super Cool Calculatorizer");
  
    * Declare and initialize two integers
+
            //Declare two variables
    * Display their values using Console.WriteLine
+
            int intOne;
    * Declare a third integer and initialize it with the sum of the first two integers
+
            int intTwo;
    * Output the value of the third integer
+
            int intSum;
  
Once the console application is done convert it to work on a web page using Response.Write instead of Console.WriteLine
+
            //intialize the two variables
 +
            intOne = 47;
 +
            intTwo = 2;
  
Top down development with comments /infod/jeff/classsource/class2/topdown.aspx
+
            //Lets test the values
Fully implemeted Console adding program /infod/jeff/classsource/class2/add.cs
+
            Console.Write("Enter a integer: ");
Conversions and Casting
+
            intOne = int.Parse(Console.ReadLine());    //set the value of intOne
 +
                                                        //to what was typed in the console
 +
            Console.Write("Enter another integer: ");
 +
            intTwo = int.Parse(Console.ReadLine());    //int.Parse attempts to parse a string
 +
                                                        //and convert it to an int
  
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.
+
            intSum = intOne + intTwo;
implicit conversion
 
  
<csharp>int intNumber = 1000;
+
            Console.WriteLine("intTwo + intTwo " + intSum);
long lngNumber;
 
lngNumber = intNumber;
 
 
int Number1= 6;
 
int Number2= 5;
 
int Number3 = Number1 / Number2;
 
//Number3 == 1 </csharp>
 
  
 +
            Console.ReadKey();
  
explicit conversion
+
        }
 +
    }
 +
}
 +
</syntaxhighlight>
  
<csharp>long lngNumber = 1000;
+
==Constants==
int intNumber;
 
intNumber = (int)lngNumber;
 
 
int Number1= 6;
 
int Number2= 5;
 
double Number3 = (double)Number1 / (double)Number2;
 
//Number3 == 1.2</csharp>
 
 
 
Constants
 
  
 
Constants are datatypes that will be assigned a value that will be constant thought the executing of the code. You cannot change constants once they have been assigned a value.
 
Constants are datatypes that will be assigned a value that will be constant thought the executing of the code. You cannot change constants once they have been assigned a value.
 
syntax
 
syntax
  
<csharp>const type identifier = value;</csharp>
+
<syntaxhighlight lang="csharp">const type identifier = value;</syntaxhighlight>
 
 
 
 
  
 
example
 
example
  
<csharp>const int freezingPoint = 32;
+
<syntaxhighlight lang="csharp">const int freezingPoint = 32;
const int freezingPointMetric = 0;
+
const int freezingPointMetric = 0;
const float pi = 3.141592</csharp>
+
const float pi = 3.141592</syntaxhighlight>
  
Arrays
 
  
Arrays are groups of variables of the same type
+
[[OOP Arrays]]
Syntax
+
{{csharp arrays}}
  
<csharp>type [] identifier</csharp>
 
  
single dimension arrays
+
==Simple Branching==
  
  <csharp>string [] aryNames = new string[3];
+
===if===
 
+
syntax
  aryNames [0] = "Joe";
 
  aryNames [1] = "Mike";
 
  aryNames [2] = "Alice";</csharp>
 
  
Example single dimensions array singleArrray.aspx  Source multi dimension arrays
+
<syntaxhighlight lang="csharp">if (expression)
 +
    // statement
 +
   
 +
if (expression) {
 +
    // statements
 +
    // statements
 +
}
 +
if (expression) {
 +
    // statements
 +
    // statements
 +
}
 +
else {
 +
    // statements
 +
}</syntaxhighlight>
  
<csharp>string [,] aryNames = new string[3,3];
+
==HomeWork==
+
*Learning c#
aryNames [0,0] = "Joe";
+
*Chapter 5, Chapter 6
aryNames [0,1] = "Schmoe";
 
aryNames [0,2] = "111 111-1111";
 
aryNames [1,0] = "Mike";
 
aryNames [1,1] = "Orbinawitz";
 
aryNames [1,2] = "222 222-2222";
 
aryNames [2,0] = "Mary";
 
aryNames [2,1] = "Alice";
 
aryNames [2,2] = "333 333-3333";</csharp>
 
 
 
Example multi dimensions array multiArrray.aspx  Source jagged arrays
 
 
 
<csharp>string [][] aryNames = new string[3][];
 
 
aryNames[0] = new string[2];
 
aryNames[1] = new string[4];
 
aryNames[2] = new string[3];
 
 
aryNames [0][0] = "John";
 
aryNames [0][1] = "Doe";
 
 
aryNames [1][0] = "James";
 
aryNames [1][1] = "Bond";
 
aryNames [1][2] = "007";
 
aryNames [1][3] = "License to kill";
 
 
aryNames [2][0] = "Mary";
 
aryNames [2][1] = "Alice";
 
aryNames [2][2] = "Im not a number im a free woman";</csharp>
 
 
 
Example jagged array jaggedArrray.aspx  Source
 
even more array samples
 
 
 
<csharp>using System;
 
 
 
class Array
 
{
 
public static void Main()
 
{
 
//array of ints
 
int[] myInts = {5,10,15};
 
Console.WriteLine("array of ints:");
 
Console.WriteLine(
 
"myInts[0]: {0}, myInts[1]: {1}, myInts[2]:{2}"
 
,myInts[0],myInts[1],myInts[2]);
 
 
 
//jagged array of bools
 
bool[][] myBools = new bool[2][];
 
myBools[0] = new bool[2];
 
myBools[1] = new bool[1];
 
 
 
myBools[0][0] = true;
 
myBools[0][1] = false;
 
myBools[1][0] = true;
 
Console.WriteLine("jagged array of bools:");
 
Console.WriteLine(
 
"myBools[0][0]: {0}, myBools[1][0]: {1}",
 
myBools[0][0], myBools[1][0]);
 
 
 
//multi-dimensional array of doubles
 
double[,] myDoubles = new double[2,2];
 
myDoubles[0, 0] = 3.147;
 
myDoubles[0, 1] = 7.157;
 
myDoubles[1, 1] = 2.117;
 
myDoubles[1, 0] = 56.00138917;
 
Console.WriteLine("multi-dimensional array of doubles:");
 
Console.WriteLine("myDoubles[0, 0]: {0}, myDoubles[1, 0]: {1}", myDoubles[0, 0], myDoubles[1, 0]);
 
  
+
Assignments
//array of strings
 
string[] myStrings = new string[3];
 
myStrings[0] = "Joe";
 
myStrings[1] = "Matt";
 
myStrings[2] = "Robert";
 
Console.WriteLine("array of strings:");
 
Console.WriteLine("myStrings[0]: {0}, myStrings[1]: {1}, myStrings[2]: {2}", myStrings[0], myStrings[1], myStrings[2]);
 
}
 
}</csharp>
 
  
==Structs
+
1.Create a simple text game that asks three questions and sets three variables. There should be a fourth variable that counts the number of correct answers. The program should run in the console and use:
  
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
+
*Console.WriteLine
Syntax
+
*Console.ReadLine
 +
*ints, strings and ifs
  
[ attributes] [access-modifiers] struct identifier
+
Analysis of Homework Project
[:interface-list {struct members}
+
*On very structured programs like this one analysis is quite easy
 +
** Start by identifying the steps
 +
** Add [http://en.wikipedia.org/wiki/Pseudocode Pseudocode] as c# comments for each step
 +
** Fill in the real syntax for each step and compile each time to make sure nothing breaks (I like to call this baby steps and I like to use this technique whenever I'm trying to implement something that is completely new to me)
  
struct Dog
+
The pseudocode might look something like
 +
<syntaxhighlight lang="csharp">using System;
 +
namespace HelloVariables
 
{
 
{
public string name;
+
    class ThreeQuestions
public string weight;
+
    {
public int age;
+
        public static void Main()
}
+
        {
+
            Console.WriteLine("3 Questions");
 +
            //A simple game that asks three questions and checks the answers. If the question is answered correctly we will award 1 point
  
==Enumerators==
+
            //Declare Variables
 
 
Enumerators are used to set predefined list of named constants.
 
Syntax
 
 
 
[ attributes] [modifiers] enum identifier
 
[:base-type {enumerator-list};
 
 
 
  //An enumerator for ServingSizes at BK
 
  enum ServingSizes : uint
 
  {
 
    Small = 0,
 
    Regular = 1,
 
    Large = 2,
 
    SuperSize = 3
 
  }
 
 
    
 
    
  //another more usefull example
+
            //Ask Question 1
  // 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
 
  }
 
 
 
 
 
==HomeWork==
 
*Learning c#
 
*Chapter 6, Chapter 7 47-84
 
  
 +
            //Read Answer
  
*Build a console application
+
            //Check Answer and add 1 to points is correct
  
  Variable Types and Casting 4pts 1 extra credit
+
            //Repeat with Questions 2 and 3
  Build a console application that declares and initializes three integers with watever values you like
 
  Display these integers in the console
 
  Cast the intergers into three floats
 
  Display the floats
 
  Cast the integers into three strings
 
  Display the strings
 
  Put the strings into an array
 
  Display the array
 
  
  extra credit use an enumerator to change word stings into ints ie "one" = 1 "two" = 2
+
            //Display Percent Correct
 +
           
 +
        }
 +
    }
 +
}</syntaxhighlight>
  
+
2. Broken Toaster Week 2 in Moodle
  
 +
3. Watch  http://www.microsoftvirtualacademy.com/training-courses/c-fundamentals-for-absolute-beginners
 +
*05 Quick Overview of the Visual C# Express Edition IDE 30 Mins
 +
*06 Declaring Variables and Assigning Values Duration 28 Mins
 +
*07 Branching with the if Decision Statement and the Conditional Operator 19 Mins
  
codetoad.com ASP.NET : HTML Server Controls
+
Download the BrokenToaster project and fix the errors so that it creates the correct output. You may change any source you need to create the output. The program flow inputs and outputs should remain in tact. Points will be awarded modifications made to achieve the correct interaction and output.
aspalliance.com - ASP.NET Syntax for Web Server Controls
 
Next week Quiz on weeks 1 and 2
 
  
 +
==Video==
 +
http://iam.colum.edu/screenz/FA13/OOP_MT/OOP_Week_2/OOP_Week_2.mp4
  
==Links==
+
[[Category:IAM Classes]]
A Comparative Overview of C#
 
Introduction to ASP .NET and Web Forms - uses VB.Net
 
Microsoft - Coding Techniques and Programming Practices
 
IBM Best Practices for Programming in C
 
GNU Coding Standards
 
GNU Naming conventions
 
RFC 2068 HTTP/1.1
 
Review
 

Latest revision as of 16:24, 10 June 2019

Posting home work and website

review Posting homework to moodle

C# fundamentals

Questions from week 1 reading. discussion

Some pages comparing c# to other languages

A Comparative Overview of C# http://genamics.com/developer/csharp_comparative.htm

C# and Java: Comparing Programming Languages http://msdn.microsoft.com/en-us/library/ms836794.aspx

Terms

CLR

Common Language Runtime https://en.wikipedia.org/wiki/Common_Language_Runtime

namespace

organizing classes with hierarchy

keyword

reserved system word

MSIL

MicroSoft Intermediary Language

JIT

Just In Time compilation @ first run https://en.wikipedia.org/wiki/Just-in-time_compilation

Everything is an Object

In c# everything is an object. And all objects inherit from the object class.

See object in the classbrowser

Since all objects inherit from the object class they all have some the basic functionality like a method called ToString();

See the source for object.cs from mono

Basic Data Types

C# is a strongly typed language. This means every object in C# must be declared to be of a specific type. All of c# basic varible type inherit from System.Object

Variable Types

.NET Types
Type Size in Bytes .Net Type Description
byte 1 Byte Unsigned (0-255)
char 2 Char Unicode Characters ascii unicode and other
bool 1 Boolean True of False
(Note: C# boolean values do not equate to integer values, or True != (read as is not equal to) 1 and False != 0)
sbyte 1 SByte Signed integers(-128 to 127)
short 2 Int16 Signed integers(-32,768 to 32,767)
ushort 2 UInt16 Unsigned integers(0 to 65,535)
int 4 Int32 Signed integers(-2,147,483,648 to 2,147,483,647)
uint 4 UInt32 Unsigned integers(0 to 4,294,967,295)
float 4 Single fixed-precision up to 7 digits. Floating point number ( 1.5 x 10-45 to 3.4 x 1038 )
double 8 Double fixed-precision up to 16 digits. Floating point number ( 5.0 x 10-324 to 1.7 x 10308 )
decimal 12 Decimal fixed-precision up to 28 digits. Typically used for financial calculations. Required the suffix "m" or "M"
long 8 Int64 Signed integer ( -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)
ulong 8 UInt64 Unsigned integer (0 to 18,446,744,073,709,551,615 )

Variables must be declared with an identifier and then initialized.

Declaration

Declaration sets aside a named section of memory the is the proper size to hold the declared type. At this point the variable contains nothing.

// declare a variable
int firstInt; //declares a vaiable of type int
string myString;  //declares a vaiable of type string

Initialization

Initialization actually sets the variables value

// initialize the variable
firstInt = 1;
myString = "Hello!";

Initialization uses the assignment operator to set the value of a variable

Assignment

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

Assignment

The Assignment operator in c# is the '=' sign. You can assign variables like this...We'll learn more about operators later.

other ways to do it

// declare some variables
int secondInt, thirdInt, fourthInt;
secondInt = 2;
thirdInt = 3;
fourthInt = 4;

//declare and initialize variables in one line
int myNegativeInt = -2147483648;

In c# variables cannot be used unil they are initalized. For example

int UsedBeforeInit;
Console.WriteLine(UsedBeforeInit);

will produce

  helloError4.cs(10,31): error CS0165: Use of unassigned local variable 'UsedBeforeInit'

Variable Names

Variable should be named with meaningful names.

for exmaple

z = x * y;

does not convey any meaning

but

distance = speed * time;

does convey meaning. If varibales are named properly it can make your code mush easier to read.

Naming conventions

Name variables intelligently.

Name variables with names that have meaning.

Hungarian Notation

Hungarian notation id a popular notation system used be many C, C++ and VB programmers. It was originally devised in Charles Simonyi's doctoral thesis, "Meta-Programming: A Software Production Method." Hungarian notation specifies that a prefix be added to each variable that indicated that variables type. It also specifies sometimes adding a suffice to clarify variables meaning. In the early 1980's Microsoft adopted this notation system.


ie... intHitCounter, intHitsPerMonthMax

Hungarian Notation - Charles Simonyi Microsoft

http://msdn.microsoft.com/en-us/library/ms229045.aspx

PascalNotation Capitalize first Letter and then the first letter on each word.

ie... PascalNotation, IntVarName

Use on method names method names.

camelNotation Lower case first letter and then capitalize the first letter of each word

ie... camelNotation, intVarName

use for variable names

Other Coding Techniques and practices

More Types

Operators

ECMA-334 Operators and punctuators

C# uses the equals = sign for Assignment

int myVar = 15;			 //sets the value of myVar to 15

Mathematical Operators

Operator Description
addition
* multiplication
/ division
% modulus remainder Ask Dr.Math What is Modulus?

Increment Decrement Operators

Operator Description
+ increment same as foo = foo + 1
-- decrement same as foo = foo - 1
= calculate and reassign addition
-= calculate and reassign subtraction
*= calculate and reassign multiplication
/= calculate and reassign division
%= calculate and reassign modulus
y= x++ assignment prefix y is assigned to x and then x in incremented
y= ++x assignment postfix x is incremented and then assigned to y

Operator Precedence

Evaluated First

  • ++,--,unary-
  • *,/,%
  • +,-

Evaluated Last

  • =,+=,-=,*=,etc


Strings

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));

</csharp>


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 \.

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
        };

Short Assignment

  Short in class Assignment
  In class assignment 10-15 mins
  Build a c# console app (remember to take a top down aproach start small with something you know maybe start with hello world)
   * Declare and initialize two integers
   * Display their values using Console.WriteLine
   * Declare a third integer and initialize it with the sum of the first two integers
   * Output the value of the third integer


Top down development with comments topdown.aspx

Fully implemented Console adding program add.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace Hello
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Super Cool Calculatorizer");

            //Declare two variables
            int intOne;
            int intTwo;
            int intSum;

            //intialize the two variables
            intOne = 47;
            intTwo = 2;

            //Lets test the values
            Console.Write("Enter a integer: ");
            intOne = int.Parse(Console.ReadLine());     //set the value of intOne 
                                                        //to what was typed in the console
            Console.Write("Enter another integer: ");
            intTwo = int.Parse(Console.ReadLine());     //int.Parse attempts to parse a string
                                                        //and convert it to an int

            intSum = intOne + intTwo;

            Console.WriteLine("intTwo + intTwo =  " + intSum);

            Console.ReadKey();

        }
    }
}

Constants

Constants are datatypes that will be assigned a value that will be constant thought the executing of the code. You cannot change constants once they have been assigned a value. syntax

const type identifier = value;


example

const int freezingPoint = 32;
const int freezingPointMetric = 0;
const float pi = 3.141592


OOP Arrays

csharp Arrays

Arrays are groups of variables of the same type Syntax

<csharp>type [] identifier</csharp>

single dimension arrays

<csharp>string [] aryNames = new string[3];

aryNames [0] = "Joe"; aryNames [1] = "Mike"; aryNames [2] = "Alice";</csharp>

Example single dimensions array singleArrray.aspx singleArray.cs

multi dimension arrays

<csharp>string [,] aryNames = new string[3,3];

aryNames [0,0] = "Joe"; aryNames [0,1] = "Schmoe"; aryNames [0,2] = "111 111-1111"; aryNames [1,0] = "Mike"; aryNames [1,1] = "Orbinawitz"; aryNames [1,2] = "222 222-2222"; aryNames [2,0] = "Mary"; aryNames [2,1] = "Alice"; aryNames [2,2] = "333 333-3333";</csharp>

Example multi dimensions array multiArrray.aspx


jagged arrays

<csharp>string [][] aryNames = new string[3][];

aryNames[0] = new string[2]; aryNames[1] = new string[4]; aryNames[2] = new string[3];

aryNames [0][0] = "John"; aryNames [0][1] = "Doe";

aryNames [1][0] = "James"; aryNames [1][1] = "Bond"; aryNames [1][2] = "007"; aryNames [1][3] = "License to kill";

aryNames [2][0] = "Mary"; aryNames [2][1] = "Alice"; aryNames [2][2] = "Im not a number im a free woman";</csharp>

Example jagged array jaggedArrray.aspx jaggedArray.cs

even more array samples

<csharp>using System;

class Array { public static void Main() { //array of ints int[] myInts = {5,10,15}; Console.WriteLine("array of ints:"); Console.WriteLine( "myInts[0]: {0}, myInts[1]: {1}, myInts[2]:{2}" ,myInts[0],myInts[1],myInts[2]);

//jagged array of bools bool[][] myBools = new bool[2][]; myBools[0] = new bool[2]; myBools[1] = new bool[1];

myBools[0][0] = true; myBools[0][1] = false; myBools[1][0] = true; Console.WriteLine("jagged array of bools:"); Console.WriteLine( "myBools[0][0]: {0}, myBools[1][0]: {1}", myBools[0][0], myBools[1][0]);

//multi-dimensional array of doubles double[,] myDoubles = new double[2,2]; myDoubles[0, 0] = 3.147; myDoubles[0, 1] = 7.157; myDoubles[1, 1] = 2.117; myDoubles[1, 0] = 56.00138917; Console.WriteLine("multi-dimensional array of doubles:"); Console.WriteLine("myDoubles[0, 0]: {0}, myDoubles[1, 0]: {1}", myDoubles[0, 0], myDoubles[1, 0]);


//array of strings string[] myStrings = new string[3]; myStrings[0] = "Joe"; myStrings[1] = "Matt"; myStrings[2] = "Robert"; Console.WriteLine("array of strings:"); Console.WriteLine("myStrings[0]: {0}, myStrings[1]: {1}, myStrings[2]: {2}", myStrings[0], myStrings[1], myStrings[2]); } }</csharp> moreArrys.cs


Simple Branching

if

syntax

if (expression)
    // statement
    
if (expression) {
    // statements
    // statements
}
if (expression) {
    // statements
    // statements
}
else {
    // statements
}

HomeWork

  • Learning c#
  • Chapter 5, Chapter 6

Assignments

1.Create a simple text game that asks three questions and sets three variables. There should be a fourth variable that counts the number of correct answers. The program should run in the console and use:

  • Console.WriteLine
  • Console.ReadLine
  • ints, strings and ifs

Analysis of Homework Project

  • On very structured programs like this one analysis is quite easy
    • Start by identifying the steps
    • Add Pseudocode as c# comments for each step
    • Fill in the real syntax for each step and compile each time to make sure nothing breaks (I like to call this baby steps and I like to use this technique whenever I'm trying to implement something that is completely new to me)

The pseudocode might look something like

using System;
namespace HelloVariables
{
    class ThreeQuestions
    {
        public static void Main()
        {
            Console.WriteLine("3 Questions");
            //A simple game that asks three questions and checks the answers. If the question is answered correctly we will award 1 point

            //Declare Variables
  
            //Ask Question 1

            //Read Answer

            //Check Answer and add 1 to points is correct

            //Repeat with Questions 2 and 3

            //Display Percent Correct
            
        }
    }
}

2. Broken Toaster Week 2 in Moodle

3. Watch http://www.microsoftvirtualacademy.com/training-courses/c-fundamentals-for-absolute-beginners

  • 05 Quick Overview of the Visual C# Express Edition IDE 30 Mins
  • 06 Declaring Variables and Assigning Values Duration 28 Mins
  • 07 Branching with the if Decision Statement and the Conditional Operator 19 Mins

Download the BrokenToaster project and fix the errors so that it creates the correct output. You may change any source you need to create the output. The program flow inputs and outputs should remain in tact. Points will be awarded modifications made to achieve the correct interaction and output.

Video

http://iam.colum.edu/screenz/FA13/OOP_MT/OOP_Week_2/OOP_Week_2.mp4