0% found this document useful (0 votes)
72 views

05 Methods and Structures

Methods are groups of statements that accomplish specific tasks. They have access modifiers, return types, names, and parameter lists. Methods are declared within classes and invoked by calling their name and passing arguments. Method overloading allows multiple methods with the same name but different parameters. Structures are value types that store related data and can contain fields, methods, and constructors. They are initialized by creating instances using default constructors.

Uploaded by

erikalast.acad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views

05 Methods and Structures

Methods are groups of statements that accomplish specific tasks. They have access modifiers, return types, names, and parameter lists. Methods are declared within classes and invoked by calling their name and passing arguments. Method overloading allows multiple methods with the same name but different parameters. Structures are value types that store related data and can contain fields, methods, and constructors. They are initialized by creating instances using default constructors.

Uploaded by

erikalast.acad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

IT1907

Methods and Structures


Methods
A method is a group of statement that accomplishes a specific task. A name is given to a method in order to call it. The general
form of defining method is
Syntax:
access_modifier return_type MethodName (parameter_list) {
//statement(s) in method body
}
The following defines the parts of a method:
• The access_modifier determines the access level or visibility of the method from another class. The modifier can be
private or public. The private modifier defines that the method can only be called in the class where it is declared,
while the public modifier defines that the method is accessible by all other classes in your application. If accessibility is
not specified, the modifier of the method is declared as private by default.
• The return_type specifies whether the method returns a value or not. The return type is the data type of the value that
the method should return using the return keyword. For example, if a method should return an integer value, the return
type should be set to int. If the method is not returning any values, then the return type is set to void.
• The MethodName is an identifier and is case sensitive. Method names should always be followed by parentheses. A
method may or may not contain a parameter list. The parameter list refers to the required type, order, and number of the
parameters of a method. Parameters are used to pass and receive data from a method.
• The method body contains a set of statements that performs the specific task of the method. These statements are
enclosed within two (2) curly braces.
Methods are declared within a class or structure by specifying the access level such as public or private, the return type, the
name of the method, and any method parameters. Together, these parts are called method signatures. In the example below,
the method signature is the public void printRectArea(int width, int height).
Example 1. The following statements defines a void method with parameter list:
//this method computes and prints the area of a rectangle of given width and height values
public void printRectArea(int width, int height) {
int area = width * height;
Console.WriteLine("The area of rectangle is " + area);
}
Example 2. The following statements defines a value returning method with parameter list:
//this method computes the area of a rectangle of given width and height values then return the result
public int getRectArea(int width, int height) {
int area = width * height;
return area;
}
Methods are invoked by typing the method name followed by parentheses. The required values, if any, are enclosedwithinthe
parentheses. These required values are called arguments. The DemoMethod.cs program shown in the code listing below
demonstrates how to create methods on the class and how to invoke them.
Code Listing 1. DemonProgram.cs
using System;

namespace ConsoleApp
{
class DemoMethod
{
static void Main(string[] args)
{
DemoMethod obj = new DemoMethod (); //this creates new instance of object
//this invoke the void method
obj.printRectArea(5, 3);

05 Handout 1 *Property of STI


[email protected] Page 1 of 4
IT1907
//this invoke the value returning method
int result = obj.getRectArea(5, 3);
Console.WriteLine("result = " + result);
}

//this method computes and prints the area of a rectangle of given width and height values
public void printRectArea(int width, int height)
{
int area = width * height;
Console.WriteLine("The area of rectangle is " + area);
}

//this method computes the area of a rectangle of given width and height values then return
the result
public int getRectArea(int width, int height) {
int area = width * height;
return area;
}
}
}
In Code Listing 1, the new instance of object named obj is created, which is used to call the methods. Additionally, the method
printRectArea is called with two (2) arguments, which are 5 and 3:
obj.printRectArea(5, 3);
This method performs its operation and does not return a value. If a method returns a value, the return data can be assigned
to a variable. In Code Listing 1, the method getRectArea is called with two (2) arguments and performs its operation then
returns a value:
int result = obj.getRectArea(5, 3);
When calling the method printRectArea or getRectArea, the width and height values are passed as arguments to the
method, which are assigned to its parameters. The method performs its operation from the values receivedthroughparameters.
Method Overloading
C# supports method overloading. Method overloading means that methods of the same name can be declared in the same
class as long as they have different sets of parameters which are determined by the number, types, and order ofthe parameters.
It is used to create several methods with the same name that perform the same or similar task, but on differenttypesordifferent
numbers of arguments. For example, the following statements define three (3) overloaded versions of getArea method,each
with a different set of parameters and different operations.
Example 3. Three (3) overloaded versions of getArea method:
//this method takes one (1) parameter and computes the area of a square
public int getArea(int side) {
int area = side * side;
return area;
}

//this method of int return type takes two (2) parameters and computes the area of a rectangle
public int getArea(int width, int height)
int area = width * height;
return area;
}

//this method of double return type takes two (2) parameters and computes the area of a rectangle
public double getArea(double width, double height)
double area = width * height;
return area;
}

05 Handout 1 *Property of STI


[email protected] Page 2 of 4
IT1907
These overloaded methods can be invoked by calling their method name and by defining the required arguments.Forexample,
assume that the name of the class is DemoOverload:
DemoOverload obj = new DemoOverload();
int square = obj.getArea(3);
int rectInt = obj.getArea(5, 3);
double rectDouble = obj.getArea(5.25, 3.25);
Console.WriteLine(square + " / " + rectInt + " / " + rectDouble);

Output:
9 / 15 / 17.0625
When an overload method is called in C#, the Common Language Runtime (CLR) compiler selects the appropriate method
depending on the number and type of defined arguments. The method overloading provides flexibility in supplyingarguments.
Structures
C# provides a value type data type called structure. Structures are used to make a single variable that holds related data of
various data types. The struct keyword is used for creating a structure. Structures are used to represent a record.The following
shows the general form how to define structures:
Syntax: Example of a struct declaration:
access_modifier struct StructName { public struct Book {
//structure members( fields, methods, and constructors) public string title;
} public string author;
public long book_id;
}
Structures can also contain constructors and methods. They are not allowed to initialize the defined struct fields. Forexample,
the field public string title = "Object-Oriented Programming"; will cause an error to the program.
To initialize struct fields, you need to create a new instance of struct object in the class using the default constructor. The
following example creates an instance of a Book struct object and initializes and accesses its individual members.
Book book1 = new Book();
//initializing struct members
book1.title = "Object-Oriented Programming";
book1.author = "John Doe";
book1.book_id = 20190001;
//accessing struct members
Console.WriteLine("Book title: " + book1.title);
Console.WriteLine("Book author: " + book1.author);
Console.WriteLine("Book ID: " + book1.book_id);
Output:
Book title: Object-Oriented Programming
Book author: John Doe
Book ID: 20190001
Structure is different from class. Structures are value types because its variables contain values, while classes are reference
types that store the memory address of where the actual value is stored. Unlike structures, instance variables of a class can be
initialized. Structures can implement an interface, but they cannot inherit from another structure.

05 Handout 1 *Property of STI


[email protected] Page 3 of 4
IT1907
Code Listing 2 shows how to write a structure and how to use it on class including its defined methods. Class and struct should
share the same namespace.
Code Listing 2. DemoStruct.cs
using System;

namespace ConsoleApp
{
public struct Book {
public string title;
public string author;
public int book_id;

//mutator method that set values of the struct fields


public void setValues(string newTitle, string newAuthor, int newBookID)
{
this.title = newTitle;
this.author = newAuthor;
this.book_id = newBookID;
}
//method that displays the values of struct fields
public void displayValues() {
Console.WriteLine("Book title: " + this.title);
Console.WriteLine("Book author: " + this.author);
Console.WriteLine("Book ID: " + this.book_id);
}
}

class DemoStruct
{
static void Main(string[] args)
{
Book book1 = new Book();
//initializing struct members
book1.title = "Object-Oriented Programming";
book1.author = "John Doe";
book1.book_id = 20190001;
//accessing struct members
Console.WriteLine("Book title: " + book1.title);
Console.WriteLine("Book author: " + book1.author);
Console.WriteLine("Book ID: " + book1.book_id);
//new instance of Book struct object and using its methods
Book book2 = new Book();
book2.setValues("C# Programming", "Jane Doe", 20190002);
book2.displayValues();
}
}
}

REFERENCES:
Deitel, P. and Deitel, H. (2015). Visual C# 2012 how to program (5th Ed.). USA: Pearson Education, Inc.
Gaddis, T. (2016). Starting out with visual C# (4th Ed.). USA: Pearson Education, Inc.
Harwani, B. (2015). Learning object-oriented programming in C# 5.0. USA: Cengage Learning PTR.

05 Handout 1 *Property of STI


[email protected] Page 4 of 4

You might also like