OOP Class2

esse quam videri
Revision as of 02:16, 10 September 2007 by Jeff (talk | contribs)
Jump to: navigation, search

<purge></purge>

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/library/default.asp?url=/library/en-us/dncenet/html/tchCJavaComparingProgrammingLanguages.asp

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.

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.

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

Initialization

Initialization actually sets the variables value

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

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

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

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

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

<csharp>int UsedBeforeInit; Console.WriteLine(UsedBeforeInit);</csharp>

will produce

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

Compiler Errors

  error
  helloError4.cs(10,31): error CS0165: Use of unassigned local variable 'UsedBeforeInit'
  file            Line        .Net Framework error # and description

Csharp Error Expected


Csharp Error error CS0116: A namespace does not
Csharp warning CS0168: The variable 'NeverUsed' is declared but never used



UsedBeforeInit.cs - example of misused variable
UsedBeforeInit_Fixed.cs - all beter now source

More examples of built in types 1x1.cs C# intrinsic types from Learn-C-Sharp. variable.aspx - example from book aspx page View Source variable2.aspx = example from book errors View Source

Variable Names

Variable shoudl 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

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
Microsoft - Coding Techniques and Programming Practices
IBM Best Practices for Programming in C
GNU Coding Standards
GNU Naming conventions
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


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.


<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 + ".");</csharp>


will output (remember \n is a new line)

    Super string theory!!!!
    Is really cool.

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

  Short in class Assignment
  In class assignment 10-15 mins
  Build a c# console app (remember to take a takedown aproach start small with somethin you know)
   * 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 implemeted Console adding program add.cs

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>

implicitConversion.cs

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>

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

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

<csharp>const type identifier = value;</csharp>


example

<csharp>const int freezingPoint = 32; const int freezingPointMetric = 0; const float pi = 3.141592</csharp>


OOP Arrays

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}

<csharp>struct Dog {

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

}</csharp>

Enumerators

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>

<csharp>//another more usefull 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 
 }</csharp>

Enumerator Example Enum.cs

HomeWork

  • Learning c#
  • Chapter 6, Chapter 7 47-84


  • Build a console application Variable Types and Casting 5pts 1 extra credit
    Build a console application that declares and initializes three integers with whatever values you like.
    Display these integers in the console using a Console.Write;
    Cast the intergers into three floats.
    Display the floats using Console.Write.
    Cast the orignal integers into three strings.
    Put the strings into an array
    Loop throught the array with a loop and display the strings in the array.
  extra credit use an enumerator to change word stings into ints ie "one" = 1 "two" = 2

Analysis of Homework Project

  • On very structured programs like the one analysis is quite easy
    • Start by indentifing the steps
    • Add Pseudocode as c# comments for each step
    • Fill in the real syntax for each step and compile each time to make usre 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 <csharp>using System; namespace HelloVariables {

   class VariablesAndCasting
   {
       public static void Main()
       {
           Console.WriteLine("Casting Examples");
           
           //declares and initializes three integers with whatever values you like
           //display these integers in the console using a Console.Write   
           
           //more steps here
       }
   }

}</csharp>