Methods and Structures in C#
Methods
Definition of a Method
- A method is a group of statements that accomplishes a specific task.
- A name is given to a method in order to call it.
Syntax of Method Definition
- General form:
access_modifier return_type MethodName(parameter_list) { //statement(s) in method body }
Parts of a Method
Access Modifier:
- Determines the access level or visibility of the method from another class.
- Can be:
- private: Method can be called only in the class where it is declared.
- public: Method is accessible by all other classes in the application.
- Default Modifier: If not specified, the method is private by default.
Return Type:
- Specifies whether the method returns a value or not.
- Indicates data type of the value returned using the
returnkeyword. - Examples:
intfor methods returning integer values.voidfor methods not returning values.
Method Name:
- An identifier for the method, which is case sensitive.
- Always followed by parentheses.
Parameter List:
- Refers to the type, order, and number of parameters of a method.
- Used to pass and receive data in methods.
Method Body:
- Contains a set of statements that perform the specific task of the method.
- Statements enclosed within two curly braces
{}.
Method Signature
- A combination of parts mentioned above. For example:
- Example Signature:
public void printRectArea(int width, int height)
- Example Signature:
Examples of Method Definitions
- Void Method Example:
```csharp
public void printRectArea(int width, int height) {
int area = width * height;
Console.WriteLine("The area of rectangle is " + area);
}
- Computes and prints area of a rectangle.
2. **Value Returning Method Example:**
csharp
public int getRectArea(int width, int height) {
int area = width * height;
return area;
}
- Computes and returns the area of a rectangle.
### Invoking Methods
- Methods are invoked by typing the method name followed by parentheses.
- Required values within parentheses are called **arguments**.
#### Code Listing 1: DemoMethod.cs
csharp
using System;
namespace ConsoleApp {
class DemoMethod {
static void Main(string[] args) {
DemoMethod obj = new DemoMethod();
// Invoke void method
obj.printRectArea(5, 3);
// Invoke value returning method
int result = obj.getRectArea(5, 3);
Console.WriteLine("result = " + result);
}
public void printRectArea(int width, int height) {
int area = width * height;
Console.WriteLine("The area of rectangle is " + area);
}
public int getRectArea(int width, int height) {
int area = width * height;
return area;
}
}
}
### Example of Method Invocation
- A new object instance named **obj** created to call methods.
- Invoked method **printRectArea**:
- `obj.printRectArea(5, 3);`
- This method performs operation, does not return a value.
- Invoked method **getRectArea**:
- `int result = obj.getRectArea(5, 3);`
- Returns a value that can be assigned to a variable.
## Method Overloading
- C# supports method overloading allowing methods of the same name in the same class with different parameter sets.
- Different sets can be defined by number, types, and order of parameters.
### Example of Overloaded Methods
**Example 3: Three Overloaded Variants of `getArea` Method:**
1. **Single parameter for square area:**
csharp
public int getArea(int side) {
int area = side * side;
return area;
}
2. **Two parameters for rectangle area (int return type):**
csharp
public int getArea(int width, int height) {
int area = width * height;
return area;
}
3. **Two parameters for rectangle area (double return type):**
csharp
public double getArea(double width, double height) {
double area = width * height;
return area;
}
### Calling Overloaded Methods
- When calling overloaded methods, the Common Language Runtime (CLR) selects the appropriate one based on argument types and counts.
- **Example of Variables:**
csharp
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);
- **Expected Output:**
9 / 15 / 17.0625
## Structures
- C# provides a value type data structure called a **structure**.
- Structures group related data of various types into a single variable.
- Defined using the `struct` keyword.
- Structures represent records.
### Syntax for Defining Structures
- General form:
csharp
access_modifier struct StructName { //structure members (fields, methods, and constructors) }
#### Example of a Struct Declaration
csharp
public struct Book {
public string title;
public string author;
public long book_id;
}
### Structure Characteristics
- Structures can have constructors and methods.
- Cannot initialize struct fields directly in their declaration.
- To initialize fields, create a new instance of the struct object using the default constructor.
#### Example of Creating and Using a Struct
csharp
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
### Structures vs. Classes
- Structures are **value types**; their members contain actual values.
- Classes are **reference types**; their variables store memory addresses of where actual values are located.
- Instance variables of classes can be initialized, while structures cannot.
- Structures can implement interfaces but cannot inherit from other structures.
#### Code Listing 2: DemoStruct.cs
csharp
using System;
namespace ConsoleApp {
public struct Book {
public string title;
public string author;
public int book_id;
// mutator method to set struct fields
public void setValues(string newTitle, string newAuthor, int newBookID) {
this.title = newTitle;
this.author = newAuthor;
this.book_id = newBookID;
}
// method to display struct field values
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 using 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.