Presentation is loading. Please wait.

Presentation is loading. Please wait.

Program Modules in C# Modules The .NET Framework Class Library (FCL)

Similar presentations


Presentation on theme: "Program Modules in C# Modules The .NET Framework Class Library (FCL)"— Presentation transcript:

1 Program Modules in C# Modules The .NET Framework Class Library (FCL)
Method The .NET Framework Class Library (FCL) Helps to increase reusability Console MessageBox Math calculations, character and string manipulations, I/O operations, error checking

2 Math Class Methods Class Math is located in namespace System (not necessary to add an assembly reference) Using methods ClassName.MethodName( argument1, arument2, … ) Example: Math.Sqrt (900.0) List of methods are in text Abs, Ceiling, Cos, Exp, Floor, Log, Max, Min, Pow, Sin, Sqrt, Tan Constants Math.PI = … Math.E = …

3 Methods Variables Reasons for using Methods
Declared in a method = local variables Declared outside a method = global variables Reasons for using Methods “Divide and conquer”  Decomposition Cut down on repetition Reusability

4 Method Definitions Writing a custom method
Header and Body same as in C++ All methods must be defined inside of a class Methods can return at most one value!!!

5 More I/O Until now Next Input from Console
Output to Console or MessageBox These can only handle one input or output value at a time Next Attaching multiple GUI components to an application and event handling Button GUI component Requires an event handler

6 Instantiation of SquareIntForm

7 Destructor InitializeComponent method in this generated code – defines non-default properties for components on form

8 Constructor Start of class SquareInt. It implements a Form {
// SquareIntForm.cs // A programmer-defined Square method using System; // includes basic data types using System.Drawing; // for graphics capabilities using System.Collections; // for complex data structures using System.ComponentModel; // controls component behavior using System.Windows.Forms; // for GUI development using System.Data; // for reading outside data namespace SquareInt { // form used to display results of squaring 10 numbers public partial class SquareIntForm : Form public SquareIntForm() InitializeComponent(); } Start of class SquareInt. It implements a Form Constructor

9 The Square method. Receives one integer and returns an integer
// Square method definition int Square( int y ) { return y * y; // return square of y } // end method Square private void calculateButton_Click (object sender, System.EventArgs e) outputLabel.Text = ""; // loop 10 times for ( int counter = 1; counter <= 10; counter++ ) // calculate square of counter and store in result result = Square( counter ); // append result to output string outputLabel.Text += "The square of " + counter + " is " + result + "\n"; } } // end calculateButton_Click } // end of class SquareInt } // end namespace Double-click on button to generate this event handler. Code it. ReInit for each button click!

10 // MaximumValue.Designer.cs
+ Windows Form Designer generated code private System.Windows.Forms.Label firstNumberLabel; private System.Windows.Forms.Label secondNumberLabel; private System.Windows.Forms.Label thirdNumberLabel; private System.Windows.Forms.Label maximumLabel; private System.Windows.Forms.TextBox firstNumberTextBox; private System.Windows.Forms.TextBox secondNumberTextBox; private System.Windows.Forms.TextBox thirdNumberTextBox; private System.Windows.Forms.Button calculateButton; Prompts for Text Boxes Input values in Text Boxes

11 double Maximum( double x, double y, double z ) {
// MaximumValueForm.cs // Finding the maximum of three double values. using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; // Method Maximum uses method Math.Max to determine the // maximum value among the three double arguments double Maximum( double x, double y, double z ) { return Math.Max( x, Math.Max( y, z ) ); } The use of Math.Max uses the Max method in class Math. The dot operator is used to call it.

12 Double.Parse( firstNumberTextBox.Text );
// get the floating-point values that the user entered and // invoke method Maximum to determine the maximum value private void calculateButton_Click (object sender, System.EventArgs e) { // get inputted values and convert strings to doubles double number1 = Double.Parse( firstNumberTextBox.Text ); double number2 = Double.Parse( secondNumberTextBox.Text ); double number3 = Double.Parse( thirdNumberTextBox.Text ); // invoke method Maximum to determine the largest value double maximum = Maximum( number1, number2, number3 ); // display maximum value maximumLabel.Text = "maximum is: " + maximum; } // end method calculateButton_Click } // end class MaximumValue } // end namespace MaximumValue Gets input from Text Boxes when button clicked Displays output in Label

13 Calling Methods Three ways to call methods Method name itself
Square (x) Maximum (num1, num2, num3) Reference to an object following by the dot operator and the method name string1.CompareTo (string2) Class name followed by dot and method name (static method) Math.Max( y, z )

14 Argument Promotion Implicit Conversion Explicit Conversion
Only done if no data will be lost Coercion of arguments to methods and in mixed-type expressions to a higher type Explicit Conversion Done with cast or class Convert in namespace System Widening - Make an object that of a derived class and more complex Narrowing - Make an object that of a base class and cause some data loss Cast Example: int result = Square ( (int ) y );

15 C# Namespaces FCL is composed of namespaces
A namespace is a group of classes and their methods Namespaces are stored in .dll files called assemblies Included in a program with the using keyword System.Console.WriteLine  Console.WriteLine Must add a reference to appropriate assembly (except for namespace System) FCL includes many names (look up “.NET Framework, class library” in the help doc)

16 C# Namespaces in FCL

17 Value Types and Reference Types Types (C# Reference) in MSDN Library
Contains data of the specified type Built in Programmer created - structs and enumerations Reference types Contain an address Built-in (string and object) Programmer created - Classes and Interfaces and Delegates All values are 32bit allowing cross-platform use

18 Passing Arguments: Call-By-Value vs. Call-By-Reference
Value types are passed by value and reference types are passed by reference To pass a value type by reference? The ref keyword specifies by-reference can modify original variable used with variables already initialized The out keyword means a called method will initialize it

19 9 // x is passed as a ref int (original value will change)
static void SquareRef( ref int x ) { x = x * x; } 14 // original value can be changed and initialized static void SquareOut( out int x ) { x = 6; x = x * x; } 21 // x is passed by value (original value not changed) static void Square( int x ) { x = x * x; } When passing a value by reference the value will be altered in the rest of the program as well Since x is passed as out the variable can then be initialed in the method Since not specified, this value is defaulted to being passed by value. The value of x will not be changed elsewhere in the program because a duplicate of the variable is created.

20 Random Number Generation
Class Random within namespace System Numbers are generated using an equation with a seed - usually the exact time of day randomObject.Next() Returns a number from 0 to Int32.MaxValue Int32.MaxValue = 2,147,483,647 randomObject.Next( x ) Returns a value from 0 up to but not including x randomObject.Next( x, y ) Returns a value between x and up to but not including y

21 16 Random randomInteger = new Random();
1 // Different RandomIntForm.cs 2 // Random integers. 4 using System; 5 using System.Windows.Forms; 6 7 // calculates and displays 20 random integers 8 public partial class RandomIntForm : Form 9 { // main entry point for application public RandomIntForm () { InitializeComponent (); int value; string output = ""; 15 16 Random randomInteger = new Random(); 17 // loop 20 times for ( int i = 1; i <= 20; i++ ) { // pick random integer between 1 and 6 value = randomInteger.Next( 1, 7 ); output += value + " "; // append value to output 24 // if counter divisible by 5, append newline if ( i % 5 == 0 ) output += "\n"; } // end for structure Creates a new Random object Will set value to a random number from1 up to but not including 7 Format the output to only have 5 numbers per line

22 RandomInt.cs Program Output
MessageBox.Show( output, "20 Random Numbers from 1 to 6", MessageBoxButtons.OK, MessageBoxIcon.Information ); } // end RandomIntForm constructor } // end class RandomIntForm Display the output in a message box RandomInt.cs Program Output

23 RollDie.cs - Rolling 4 dice.

24 20 private System.Windows.Forms.Label dieLabel1;
// THE AUTO GENERATED CODE for the application RollDie private System.ComponentModel.Container components = null; private System.Windows.Forms.Button rollButton; 20 private System.Windows.Forms.Label dieLabel1; 21 private System.Windows.Forms.Label dieLabel2; 22 private System.Windows.Forms.Label dieLabel3; 23 private System.Windows.Forms.Label dieLabel4; 1 // RollDie.cs: Rolling 4 dice. 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; 10 using System.IO; // enables reading data from files 11 24 26 // form simulates the rolling of 4 dice, and displays them 14 public partial class RollDieForm : Form 15 { private Random randomNumber = new Random(); public RollDieForm() { InitializeComponent(); } 32

25 41 DisplayDie( dieLabel1 );
// method called when rollButton clicked, passes labels to another method protected void rollButton_Click( object sender, System.EventArgs e ) { // pass the labels to a method that will // randomly assign a face to each die DisplayDie( dieLabel1 ); DisplayDie( dieLabel2 ); DisplayDie( dieLabel3 ); DisplayDie( dieLabel4 ); } // end rollButton_Click 47 // determines image to be displayed by current die 49 public void DisplayDie( Label dieLabel ) { int face = 1 + randomNumber.Next( 6 ); 52 // displays image specified by filename dieLabel.Image = Image.FromFile(Directory.GetCurrentDirectory() + "\\images\\die" + face +".gif" ); } Pass the labels to be assigned data Will return a random integer from 0 up to 6

26

27 17 private System.Windows.Forms.Button rollButton;
private System.Windows.Forms.RichTextBox displayTextBox; private System.Windows.Forms.Label dieLabel1; : private System.Windows.Forms.Label dieLabel12; 33 1 // RollDie2Form.cs: Rolling 12 dice with frequency chart. 12 // displays the different dice and frequency information 13 public partial class RollDie2Form : Form { private Random randomNumber = new Random(); private int ones, twos, threes, fours, fives, sixes; public RollDie2Form() { InitializeComponent(); ones = twos = threes = fours = fives = sixes = 0; 42 } Sets all of the variables to 0

28 46 // simulates roll by calling DisplayDie for each label and displaying the results
protected void rollButton_Click( object sender, System.EventArgs e ) { // pass labels to a method that randomly assigns a face to die DisplayDie( dieLabel1 ); : DisplayDie( dieLabel12 ); double total = ones + twos + threes + fours + fives + sixes; 67 Pass the label to be assigned a random number

29 68 // display the current frequency values
displayTextBox.Text = "Face\t\tFrequency\tPercent\n1\t\t" + ones + "\t\t" + String.Format( "{0:F2}", ones / total * 100 ) + "%\n2\t\t" + twos + "\t\t" + String.Format( "{0:F2}", twos / total * 100 ) + "%\n3\t\t" + threes + "\t\t" + String.Format( "{0:F2}", threes / total * 100 ) + "%\n4\t\t" + fours + "\t\t" + String.Format( "{0:F2}", fours / total * 100 ) + "%\n5\t\t" + fives + "\t\t" + String.Format( "{0:F2}", fives / total * 100 ) + "%\n6\t\t" + sixes + "\t\t" + String.Format( "{0:F2}", sixes / total * 100 ) + "%"; } // end rollButton_Click 84 // display the current die, and modify frequency values public void DisplayDie( Label dieLabel ) { int face = 1 + randomNumber.Next( 6 ); dieLabel.Image = Image.FromFile( Directory.GetCurrentDirectory() + "\\images\\die" + face + ".gif“ ); Assign a random face to the label based on the number generated

30 A switch statement is used to keep track of number of each die rolled
// add one to frequency of current face switch ( face ) { case 1: ones++; break; case 2: twos++; break; case 3: threes++; break; case 4: fours++; break; case 5: fives++; break; case 6: sixes++; break; } // end switch } // end DisplayDie A switch statement is used to keep track of number of each die rolled

31 12 labels A button with a click event DisplayTextBox

32 Example: Game of Chance
GUI controls GroupBox Holds other controls Manages and organizes them PictureBox Used to display a picture on the form

33 29 // declare other variables 30 int myPoint; 31 int myDie1;
private System.ComponentModel.Container components = null; 15 private System.Windows.Forms.PictureBox imgPointDie1; private System.Windows.Forms.PictureBox imgPointDie2; private System.Windows.Forms.PictureBox imgDie2; private System.Windows.Forms.PictureBox imgDie1; 19 private System.Windows.Forms.Label lblStatus; 21 private System.Windows.Forms.Button rollButton; private System.Windows.Forms.Button playButton; 24 private System.Windows.Forms.GroupBox fraPoint; 1 // CrapsGameForm.cs 12 public partial class CrapsGameForm : Form 13 { 28 // declare other variables int myPoint; int myDie1; int myDie2; 33 Global variables

34 34 public enum DiceNames 35 { 36 SNAKE_EYES = 2, 37 TREY = 3,
{ SNAKE_EYES = 2, TREY = 3, CRAPS = 7, YO_LEVEN = 11, BOX_CARS = 12, } // simulate next roll and result of that roll protected void rollButton_Click( object sender, System.EventArgs e ) { int sum; sum = rollDice(); 56 if ( sum == myPoint ) { lblStatus.Text = "You Win!!!"; rollButton.Enabled = false; playButton.Enabled = true; } Creates an enumeration of the constant values in craps When the second rolled sum equals the first rolled sum the player wins

35 63 else 64 if ( sum == ( int )DiceNames.CRAPS )
{ lblStatus.Text = "Sorry. You lose."; rollButton.Enabled = false; playButton.Enabled = true; } 70 } // end rollButton_Click 72 // simulate first roll and result of that roll protected void playButton_Click(object sender, System.EventArgs e ) { int sum; myPoint = 0; fraPoint.Text = "Point"; lblStatus.Text = ""; imgPointDie1.Image = null; imgPointDie2.Image = null; 83 sum = rollDice(); 85 Casting enum type to an int using explicit conversion

36 104 displayDie( imgPointDie2, myDie2 );
switch ( sum ) { case ( int )DiceNames.CRAPS: case ( int )DiceNames.YO_LEVEN: rollButton.Enabled = false; // disable Roll button lblStatus.Text = "You Win!!!"; break; case ( int )DiceNames.SNAKE_EYES: case ( int )DiceNames.TREY: case ( int )DiceNames.BOX_CARS: rollButton.Enabled = false; lblStatus.Text = "Sorry. You lose."; break; default: myPoint = sum; fraPoint.Text = "Point is " + sum; lblStatus.Text = "Roll Again"; displayDie( imgPointDie1, myDie1 ); displayDie( imgPointDie2, myDie2 ); playButton.Enabled = false; rollButton.Enabled = true; break; } // end switch } // end playButton_Click If on the first roll the players gets a 7 or an 11 they win If the first roll is a 2, 3 or 12, the player loses. Any other number allows the player to roll again

37 126 die1 = randomNumber.Next( 1, 7 );
// simulates the rolling of two dice private int rollDice() { int die1, die2, dieSum; Random randomNumber = new Random(); 125 die1 = randomNumber.Next( 1, 7 ); die2 = randomNumber.Next( 1, 7 ); 128 displayDie( imgDie1, die1 ); displayDie( imgDie2, die2 ); 131 myDie1 = die1; myDie2 = die2; dieSum = die1 + die2; return dieSum; 136 } // end rollDice Generates two random numbers, one for each die

38 CrapsGame.cs Program Output

39 Duration of Identifiers
The amount of time an identifier exists in memory Local variables of a method Automatic duration: Created when declared and destroyed when the block exits Not initialized Instance variables of a class Initialized by compiler, if not done by programmer Most variables are set to 0, false or null

40 Scope Rules Scope Class scope Block scope
Portion of a program in which a variable can be accessed Class scope From when created in class until end of class (}) Global to all methods in that class Repeated names causes previous to be hidden until scope ends Block scope From when created until end of block (}) Only used within that block Cannot repeat variable names

41 Will output the value of 5
2 // A Scoping example. 11 private System.ComponentModel.Container components = null; private System.Windows.Forms.Label outputLabel; public partial class Scoping : Form { public int x = 1; 17 public Scoping() { InitializeComponent(); 21 int x = 5; // variable local to constructor 23 outputLabel.Text = outputLabel.Text + "local x in method Scoping is " + x; 26 MethodA(); // MethodA has automatic local x; MethodB(); // MethodB uses instance variable x MethodA(); // MethodA creates new automatic local x MethodB(); // instance variable x retains its value 31 outputLabel.Text = outputLabel.Text + "\n\nlocal x in method Scoping is " + x; } This variable has class scope and can be used by any method in the class This variable is local only to Scoping. It hides the value of the global variable Will output the value of 5 Remains 5 despite changes to global version of x

42 public void MethodA() { int x = 25; // initialized each time a is called 41 outputLabel.Text = outputLabel.Text + "\n\nlocal x in MethodA is " + x + " after entering MethodA"; x; outputLabel.Text = outputLabel.Text + "\nlocal x in MethodA is " + x + " before exiting MethodA"; } public void MethodB() { outputLabel.Text = outputLabel.Text + "\n\ninstance variable x is " + x + " on entering MethodB"; x *= 10; outputLabel.Text = outputLabel.Text + "\ninstance varable x is " + x + " on exiting MethodB"; } Uses a new x variable that hides the value of the global x Uses the global version of x (1) Will permanently change the value of x globally

43 Scoping.cs Program Output

44 Recursion Same as C++

45 Method Overloading Methods with the same name
Can have the same name but need different arguments Variables passed must be different Either in number, type received, or order sent Usually perform the same task On different data types

46 21 // call both versions of Square 22 outputLabel.Text =
private System.ComponentModel.Container components = null; private System.Windows.Forms.Label outputLabel; 1 // MethodOverloadForm.cs 11 public partial class MethodOverloadForm : Form 12 { 16 public MethodOverloadForm() { InitializeComponent(); 20 // call both versions of Square outputLabel.Text = "The square of integer 7 is " + Square( 7 ) + "\nThe square of double 7.5 is " + Square ( 7.5 ); } Two versions of the square method are called

47 MethodOverload.cs Program Output
// first version, takes one integer public int Square ( int x ) { return x * x; } 34 // second version, takes one double public double Square ( double y ) { return y * y; } One method takes an int as parameters MethodOverload.cs Program Output The other version of the method uses a double instead of an integer

48 MethodOverload2.cs Program Output
1 // Overloaded methods with identical signatures and different return types. 6 7 class MethodOverload2 8 { 9 public int Square( double x ) { return x * x; } 13 // second Square method takes same number, order and type of arguments, error 16 public double Square( double y ) { return y * y; } MethodOverload2.cs Program Output This method returns an integer This method returns a double number Since the compiler cannot tell which method to use based on passed values an error is generated


Download ppt "Program Modules in C# Modules The .NET Framework Class Library (FCL)"

Similar presentations


Ads by Google