380 Study

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

Methods –

Purpose of methods: To break a program down into small, manageable pieces.


This process is known as the divide and conquer approach

Modularization: Breaking down a program into smaller units of code such as methods
Top-Down Design: Breaking down an algorithm into methods. Breaks overall task of program
into subtasks

There are two types of methods:


1) Void Method: Executes a group of statements and then terminates
2) Value-returning: Returns a value to the statement that called it

A method consists of a Header and a Body -


Method Header: This indicates the access modifier, the return type, and the method name
followed by a pair of parentheses
Method Body: Collection of statements that are performed when method is called

Format of a Method Header:

Access Modifier Return Type Method Name(parameterList);


{
Method Body
}

1) Access Modifier:
Private  called only by code inside same class as method
Public  can be called by code outside of the class

2) Return Type: Can be Void or Value Returning


3) Method Name: Unique to the Method(Uses Pascalcase) followed by a parentheses

Ex of Method:
Private void DisplayMessage()
{
Messagebox.show(“This is the display message Method”);
}

Call statements: Methods are executed by call statements – format is the name of the method
followed by parentheses

Return point: Memory address of location to which method should return, the system needs
to know where program should return after method ends
Argument: Any piece of data that is passed into a method
Parameter: A variable that receives an argument that is passed into a method, usually
consisting of a data type, and variable name

Two ways to pass an argument by reference:


When either two ways are used – you must write the keyword ‘out’ or ‘ref’ before the
argument i.e
Int myVar;
SetToZero(out myVar);

Or
Int myVar = 99;
SetToZero(ref myVar);

Note: Output parameters do not have have a value attached to it like Reference variables do

1) Output Parameter: Declare by using the ‘out’ keyword before the parameter variables
data type
Ex: Private void SetToZero( out int number)
{
number = 0
}

2) Reference Parameter: Declare by using the ‘ref’ keyword before parameter variables
data type
Ex: Private void SetToZero( ref int number)
{
number = 0
}
Arrays/Lists –
Two categories that data types fall into for C#/.NET framework
1) Value types: Variable used to hold a value, such as 23. Actually holds data

2) Reference types: Variable used to reference an object, used to reference objects and
does not hold data. Links the variable that holds data to the object

Array: Allows you to store a group of items of the same data type together in memory.
Variables are not ideal for storing/processing lists of data so use arrays. Arrays are reference
type objects.

Declaring an Array: Two steps to creating an Array –


1) Declare reference type object
2) Create object and associate it with reference variable

Format of an Array:
1) DataType[ ]arrayName;
arrayName = new DataType[Array size];

 ‘New’ is the keyword that creates an object in memory


Ex:
int[ ] numbersArray;
numbersArray = new int [Array size]

2) DataType[ ] arrayName = new DataType[Array size]


Ex:
string[ ] namesArray = new string[Array size]

3) Const int SIZE = [6]


DataType[ ] arrayName = new DataType[SIZE]
Ex:
Cons int SIZE = [8]
String[ ] nameArray = new string[SIZE]

 Size declarator must be positive integer

4) Const int SIZE = [5]


DataType[ ] arrayName = new DataType [SIZE] {10, 20, 30, 40, 50}
Ex:
Const int SIZE = [6]
int[ ] numbersArray = new int [SIZE] {10, 20, 30, 40, 50, 60}
5) DataType[ ] arrayName = new DataType[ ] {10, 20, 30, 40, 50}
Ex:
string[ ] namesArray = new String [ ] {“bill” , “Jill” , “phil” , “ill” , “will”}

6) DataType[ ] arrayName = {10, 20, 30, 40, 50}


Ex:
int [ ] numbersArray = {10, 20, 30, 40, 50}

Elements: Storage locations in arrays, each element in an array is assigned a unique number
known as a subscript
Subscript: Starts with 0, used to identify specific elements in an array

 You can access each individual element by using their subscript

Ex:
Const int SIZE = 6
Int [] numbersArray = new int [SIZE]
numbersArray[0] = 20
numbersArray[1] = 31
numbersArray[2] = 24
numbersArray[3] = 26

To get value of 3rd element do:


numbersArray[2]

Files/Arrays:

StreamWriter outputFile: To write arrays content to a file


int[ ] numbersArray = {10, 20, 30, 40, 50};
StreamWriter outputFile;
outputFile = File.CreateText(“values.txt”)

StreamReader inputFile: To read values from file and store in an array


Int[ ] numbersArray = {10, 20, 30, 40, 50}
Int index = 0
StreamReader inputFile
inputFile = File.OpenText(“values.txt”)
Passing an Array as an argument to methods:
 An entire array can be passed as one argument to a method
String [ ] people = {“Jill” , “Will”, “Phil”, “Bill”}
showArray(people)
private void ShowArray(string[ ] strArray)
{
foreach (string str in StrArray)
{
Messagebox.Show(str)
}

2-Dimensional Arrays:
 Stores multiple sets of data
 Illustrated with rows and columns

Declaring 2-D Arrays:


Double [ , ] scores = new double [3,4]

Const int ROWS = 3


Const int COLS = 4
Double [ , ] scores = new double[ROWS, COLS]

Accessing elements in 2-D Array:


Each element has 2 subscripts, one for rows and one for columns

Double[ ,] scores = new double [3,4]


Scores[0,0]
Scores[0,1]
Scores[0,2]
Scores[0,3]

To assign values to elements in 2-D

Double[ , ] scores = new double [3,4]


Scores[0,0] = 24
Scores[0,1] = 28

Simplified Declaration of 2-D Array:


Int[ , ] scores = {71, 67, 45, 82}
{54, 87, 22, 21}
{80, 75, 62, 25}
Properties/Methods of Array Class:
Length: Gets number of elements in array in all dimensions
GetLength(dimension): Get number of elements in specified dimension of array
GetUpperBound(dimension): gets index of last element in specified dimension of an array
Copy(array1, array 2, length): copies values of array to another array

Lists:
 Class in .NET framework that is similar to an array with the following advantages:
1) List object does not require size declaration
2) You can add or remove items from a list

Format of a list:
List <DataType> ListName = new List <DataType> ();

Ex:
List<String>namesList = new List <String>();
List<Int>numbersList = new List <Int>();

Add items to a list:


List<String> namesList = new List<String>();
namesList.Add(“Chris”)
namesList.Add(“Bill”)

Insert item at a specified index in list:


List<String> namesList = new List<String>();
namesList.Insert(“Joanne”, 0)

Remove items from a list:


List<String> namesList = new List <String>();
namesList.Remove(“Bill”)

Using RemoveAt to remove an item at a specified index in list:


List<string>namesList = new List<String>();
nameList.RemoveAt(0);

Using Count to access all items in the list


Count holds the number of items stored in a list

Formats for declaring lists:


1) List <datatype> listname = new List <datatype>() {1,2,3}
2) List <string> namesList= new List<string>() {“Christ” , “Bill” , “Kathryn”}
Classes –
Architecture of a 3-layered application
1) Presentation layer  Main windows Form
2) Middle layer  Business classes
3) Database layer  Database classes

Object: Self-contained unit with properties, methods, and other members


 Class contains code that defines members of an object
 An object is an instance of a class, process of creating an object is called instantiation

Encapsulation: Fundamental concept of OOP. Let’s you control data and operations within a
class that are exposed to other classes

Data hiding: Data of a class is typically encapsulated within a class

 Classes usually consist of methods, properties, and constructors

Class Declaration Format:


Class className || classheader
{
member declaration
}

Class Header: Start with keyword class, followed by name of class


Member Declaration: Statements that define the classes fields, properties, and methods
Constructors: Special method automatically executed when an object is created

Property: Class member that holds a piece of data about an object, can be implemented as
special methods that set and get the value of corresponding fields

Accessors: Set and Get Methods

Backing field: Used to hold any data assigned to name property


Value Parameter: Set accessor is automatically created by the compiler

Get accessor: if not empty, is a method that returns the property’s value because it has a return
statement. Executed when the property is read.

Set accessor: if not empty, gets the value stored in the backing field and assigns the value to the
property

 Get-Set uses an implicit parameter named Value


 Executed whenever a value is assigned to the property
Parametrized Constructor: Constructor that accepts arguments

Overloaded methods: A class can have multiple versions of the same method. This is a method
with the same name but different parameters.
Signature of a method: Consists of method name, datatype, argument kind

Binding: Process of matching a method call with the correct method

ShowDialogue: Displays a form on the screen and it gives that form the focus

ModalForm: or Dialogue box, must be closed or hidden before you can continue working with
the rest of the application. When declard, no other form in the application can receive the
focus until modal form is closed.
ModelessForm: Allows user to switch focus to another form while it is displayed

*Product Class
Public class product
{
Private String Code
Private String Description
Private Decimal Price

Public Product ()()

Public Product(String code, string description, decimal price)


(
this.code = code/
this.description = description/
this.price = price/
)

Public string code


(
Get
( return code/
)
Set
( code = value/
)
)
Public String Description
(
get
(
return description
)
set
( description = value/
)
Public decimal price
(
get
(
return price/
)
set
( price = value/
)

public string GetDisplayText(String sep )


(
return code + sep + price.ToString(“c”) + sep + description
)
)
Inheritance –
 Inheritance allows a new class to extend to an existing class
 New class inherits members of class it extends
 Helps to specialize a class from an existing class
 Helps to generalize common members of many classes into a new class

Is-a relationship: When one object is a specialized version of another object, relationship exists
Ex:
grasshopper is an insect
bumblebee is an insect
specialization is a generalization

Logic behind relationship: All insects have certain common characteristics and can be described
by an insect class. Grasshoppers and bumblebees have unique characteristics and can be
described by a grasshopper class and a bumblebee class

Is-a relationship implies specialized object has all characteristics of the generalized object
Specialized object has additional characteristics that make it special, general objects do
not have them
Is-a relationship allows you to extend capabilities of a class by creating another class that is a
specialized version of it

Inheritance: Consists of base and derived classes


Base class: generalized class also known as superclass
Derived class: specialized class sometimes called subclass

Polymorphism: objects ability to take many forms. Allows derived classes to have methods with
same names as methods in their base classes. Gives ability for a program to call the correct
method. When a derived class inherits from a base class, it gains all the methods, fields,
properties, and events of the base class.

 In order for an instance of a derived class to completely take over a class member from a
base class, the base class has to declare that member as virtual
 Fields cannot be virtual
 Only methods, properties, and events can be virtual

A derived class has the option of using the override keyword to replace the base class
implementation with its own

Abstract Class: Serves as a base class but is not instantiated itself. Only provides some class
members to its derived classes

You might also like