Master C# Methods: Learn Syntax, Parameters & Examples
Methods and Functions
In this section, we will explore methods in C#, one of the foundational building blocks of any C# program. By the end, you’ll understand what methods are, how to define and use them, and how to make your code cleaner and more efficient.
What are Methods?
Methods are reusable blocks of code designed to perform specific tasks. Think of methods as the instructions you give your program to execute certain operations.
Benefits of Using Methods
For example, if you need to calculate the area of a rectangle multiple times in your program, you can define a method called CalculateArea instead of writing the calculation logic repeatedly.
Defining and Calling Methods
Defining a Method
A method in C# is defined using the following syntax:
[access_modifier] [return_type] MethodName([parameters])
{
// Code to execute
}
Example: Defining and Calling a Static Method
using System;
class Program
{
static void Main()
{
int result = AddNumbers(5, 7); // Calling the method
Console.WriteLine($"The result is: {result}");
}
static int AddNumbers(int a, int b) // Defining the method
{
return a + b;
}
}
Output:
The result is: 12
Example: Defining and Calling an Instance Method
using System;
class Calculator
{
public int MultiplyNumbers(int x, int y)
{
return x * y;
}
}
class Program
{
static void Main()
{
Calculator calc = new Calculator(); // Create an object
int product = calc.MultiplyNumbers(4, 6); // Call the instance method
Console.WriteLine($"The product is: {product}");
}
}
Output:
The product is: 24
Parameters and Return Values
Parameters
Methods can accept parameters to work with data passed to them.
领英推荐
Example: Passing Parameters
static void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
static void Main()
{
Greet("Alice"); // Output: Hello, Alice!
Greet("Bob"); // Output: Hello, Bob!
}
Return Values
Methods can return values to the caller using the return keyword.
Example: Using Return Values
static double CalculateCircleArea(double radius)
{
return Math.PI * radius * radius;
}
static void Main()
{
double area = CalculateCircleArea(5);
Console.WriteLine($"The area is: {area}");
}
Value vs Reference Parameters
Example: Reference Parameter
static void Increment(ref int number)
{
number++;
}
static void Main()
{
int count = 10;
Increment(ref count);
Console.WriteLine(count); // Output: 11
}
Method Overloading
Method overloading allows multiple methods with the same name but different parameter lists.
Example: Overloaded Methods
static int Add(int a, int b)
{
return a + b;
}
static int Add(int a, int b, int c)
{
return a + b + c;
}
static void Main()
{
Console.WriteLine(Add(3, 4)); // Output: 7
Console.WriteLine(Add(1, 2, 3)); // Output: 6
}
Overloading makes your code more flexible and intuitive to use.
Practical Examples and Exercises
Example 1: Calculate the Area of a Rectangle
static int CalculateRectangleArea(int length, int width)
{
return length * width;
}
static void Main()
{
Console.WriteLine(CalculateRectangleArea(5, 10)); // Output: 50
}
Example 2: Check if a Number is Prime
static bool IsPrime(int number)
{
if (number <= 1) return false;
for (int i = 2; i < number; i++)
{
if (number % i == 0) return false;
}
return true;
}
static void Main()
{
Console.WriteLine(IsPrime(7)); // Output: True
Console.WriteLine(IsPrime(10)); // Output: False
}
References and citations:-
Senior Software Engineer at WatchGuard Technologies
2 个月Go and checkout this quiz on c#: https://youtube.com/shorts/I8VaW4bKbI0
Automation QA Engineer | Cypress.io | Robot Framework | Playwright | JavaScript | Cucumber BDD | Blockchain & AI Enthusiast
2 个月Insightful