Methods in C# Language
C# (pronounced as “C sharp”) is a popular, versatile, and object-oriented programming language d
eveloped by Microsoft. It offers a wide range of features, and one of the fundamental building blocks of C# programs is methods. Methods allow you to encapsulate logic and functionality within your code, making it more organized, readable, and maintainable. In this article, we will delve into the world of methods in C# and explore various types and examples.Defining Methods:
In C#, a method is a block of code that performs a specific task or operation. It can be part of a class or a stand-alone method. When defining a method, you specify its name, access modifier, return type, parameters (if any), and method body. Here’s a basic structure of a C# method:
access_modifier return_type MethodName(parameters)
{
// Method body
// Perform operations
return result; // (optional)
}
access_modifier
: Defines the accessibility of the method (e.g.,public
,private
,protected
,internal
).return_type
: Specifies the data type of the value the method returns. If the method doesn’t return anything, usevoid
.MethodName
: The name of the method.parameters
: Optional input values that the method can use.method body
: Contains the code to perform the desired task.return
: If the method has a return type, it returns a value of that type.
Example 1: A Simple Method
Let’s create a simple method that calculates the sum of two numbers and returns the result:
public int Add(int num1, int num2)
{
int sum = num1 + num2;
return sum;
}
In this example:
- Access modifier is
public
. - Return type is
int
. - Method name is
Add
. - Two parameters,
num1
andnum2
, are of typeint
. - The method body calculates the sum of
num1
andnum2
and returns the result.
Example 2: Static Methods
Static methods belong to the class itself, not to instances of the class. They are defined using the static
keyword and can be called without creating an instance of the class. Here’s an example:
public static void PrintMessage(string message)
{
Console.WriteLine(message);
}
In this example:
- Access modifier is
public
. - Return type is
void
. - Method name is
PrintMessage
. - One parameter,
message
, is of typestring
. - The method body prints the message to the console.
Example 3: Method Overloading
Method overloading allows you to define multiple methods with the same name in a class but with different parameter lists. The appropriate method is chosen at compile time based on the number or types of arguments provided.
public int Add(int num1, int num2)
{
return num1 + num2;
}
public double Add(double num1, double num2)
{
return num1 + num2;
}
In this example, we have two Add
methods with different parameter types (int and double). Depending on the argument types, the appropriate method is called.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.