Methods in C#
A method is a basic building component of C# programming, consisting of a block of code with a number of statements. In C#, every instruction that is performed takes place inside a method. Methods are made to carry out particular tasks; they can optionally take parameters as input and output a result.
Why Use Methods?
There are various reasons why methods are so helpful.
Modularity and Structure: Your code will become more structured and legible as a result of their ability to divide your program logic into discrete, manageable components.
Code Reusability: A specific piece of code can be encased within a method and called again to prevent duplication if it is required in several places within a program. This has a lot to do with the idea of code reuse.
Maintainability: Developers can more easily maintain and make changes to well-organised and understandable code over time with the help of methods.
Encapsulation and Data Protection: In order to prevent incorrect or unauthorised modifications to the data, methods can offer a restricted method of accessing and modifying data fields within a class.
Method Declaration and Signatures
The compiler is given information about a method’s properties via its declaration. The general syntax consists of:
Access Modifier: Establishes the method’s visibility or scope (e.g., public, private, protected, internal
).
Optional Modifier: Static, abstract, virtual, override, and new
are examples of keywords that give further details about how the method behaves.
Return Type: Identifies the kind of value that the method will yield. The return type of a method is void if it returns nothing.
Method Name: An authentic C# identifier that explains the goal of the method.
Parameter List: This is a list of the names and types of input arguments that the method expects, enclosed in brackets () and separated by commas. Empty brackets () are still necessary even if parameters are not needed.
Method Body: Immediately below the declaration, enclosed in curly braces {}, is the actual code (logic and instructions) that the function uses.
In object-oriented programming, the method signature plays a vital role in identifying a method. The method’s name and parameter list (types, order, and number of parameters) are all that are included. Crucially, the return type is not included in the signature of the method. Accordingly, even if two methods have different return types, they cannot share the same name or parameter list.
Method Declaration Syntax
[AccessModifier] [OptionalModifier] ReturnType MethodName(ParameterType1 parameter1, ParameterType2 parameter2)
{
// Method body: code to be executed
// Optional: return result;
}
Types of Methods
Non-Static Methods (Instance Methods)
- These methods are part of a class’s particular instance, or object.
- Both the class’s static members and instance members (fields, properties) are accessible to them.
- An object of the class must be created before you can call an instance method.
Example
using System;
// 1. Define a Class
public class Dog
{
// 2. Define an Instance Field (data specific to each Dog object)
public string Name;
public string Breed;
// 3. Define a Non-Static Method (Instance Method)
// It uses the instance fields (Name, Breed) of the specific Dog object.
public void Bark()
{
Console.WriteLine($"{Name} ({Breed}) says: Woof! Woof!");
}
// Another Non-Static Method
public void Introduce()
{
Console.WriteLine($"Hi, my name is {Name} and I am a {Breed}.");
}
}
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("--- Demonstrating Non-Static Methods ---");
// 4. Create an instance (object) of the Dog class
Dog dog1 = new Dog();
dog1.Name = "Buddy";
dog1.Breed = "Golden Retriever";
// 5. Call non-static methods on the 'dog1' object
Console.WriteLine("\nActions for Dog 1:");
dog1.Introduce(); // Calls Introduce() on dog1's data
dog1.Bark(); // Calls Bark() on dog1's data
Console.WriteLine("----------------------------------");
// 6. Create another instance (object) of the Dog class
Dog dog2 = new Dog();
dog2.Name = "Lucy";
dog2.Breed = "Labrador";
// 7. Call non-static methods on the 'dog2' object
// Notice how these methods use 'Lucy' and 'Labrador' because they are operating
// on the data of the 'dog2' instance.
Console.WriteLine("\nActions for Dog 2:");
dog2.Introduce(); // Calls Introduce() on dog2's data
dog2.Bark(); // Calls Bark() on dog2's data
Console.WriteLine("\n--- End of Demonstration ---");
}
}
Output
--- Demonstrating Non-Static Methods ---
Actions for Dog 1:
Hi, my name is Buddy and I am a Golden Retriever.
Buddy (Golden Retriever) says: Woof! Woof!
----------------------------------
Actions for Dog 2:
Hi, my name is Lucy and I am a Labrador.
Lucy (Labrador) says: Woof! Woof!
--- End of Demonstration ---
Static Methods
- Rather than being specific to any one instance of the class, these methods are part of the class itself.
- They are only able to directly access other static class members.
- Using the class name, you can invoke a static method without first constructing an object. All C# executable applications must start with the Main() function, which needs to be static.
Example
using System;
// 1. Define a Static Class (optional, but common for utility methods)
// A static class can only contain static members.
public static class MathOperations
{
// 2. Define a Static Method
// Notice the 'static' keyword before the return type.
// This method performs a calculation that doesn't depend on any specific 'MathOperations' object.
public static int Add(int a, int b)
{
return a + b;
}
// Another Static Method
public static int Subtract(int a, int b)
{
return a - b;
}
// A static field (data belonging to the class, not an object)
public static double Pi = 3.14159;
// A static method that uses a static field
public static double CalculateCircleArea(double radius)
{
// We use the static 'Pi' field directly
return Pi * radius * radius;
}
}
// 3. Define a Regular Class with a Static Method (like Main)
public class MessageUtility
{
// A static method that doesn't belong to a static class
public static void DisplayWelcomeMessage(string userName)
{
Console.WriteLine($"Welcome, {userName}! Hope you have a great day.");
}
}
public class Program
{
// Main method is always static because the program needs to start execution
// without creating an instance of the Program class.
public static void Main(string[] args)
{
Console.WriteLine("--- Demonstrating Static Methods ---");
// 4. Call Static Methods directly on the Class Name
// No need to create an object like 'new MathOperations()'.
int sum = MathOperations.Add(10, 5);
Console.WriteLine($"10 + 5 = {sum}"); // Output: 10 + 5 = 15
int difference = MathOperations.Subtract(20, 7);
Console.WriteLine($"20 - 7 = {difference}"); // Output: 20 - 7 = 13
// Accessing a static field directly
Console.WriteLine($"Value of Pi: {MathOperations.Pi}"); // Output: Value of Pi: 3.14159
// Using a static method that uses a static field
double area = MathOperations.CalculateCircleArea(5.0);
Console.WriteLine($"Area of circle with radius 5: {area}"); // Output: Area of circle with radius 5: 78.53975
Console.WriteLine("\n--- End of Demonstration ---");
}
}
Output
--- Demonstrating Static Methods ---
10 + 5 = 15
20 - 7 = 13
Value of Pi: 3.14159
Area of circle with radius 5: 78.53975
--- End of Demonstration ---
Method Parameters
To feed data into a method, parameters are utilized. There are three primary methods for passing parameters:
By Value: The value of the argument is supplied to the method as a copy. The original argument remains unaffected when the parameter inside the method is changed.
Output Parameters (out
): Utilized to return results from a method. When the out keyword is used, it means that the argument is supplied by reference and that the method must assign a value to it before returning.
Reference Parameters (ref
): Used for reference-based argument passing. The original argument will be impacted if the parameter is altered inside the method. Both when invoking the method and in the method declaration, the ref keyword must be used.
Parameter Arrays (params
): Gives a method the ability to take a variable number of arguments of a certain type.
Code Example: Method with Parameters and Return Value
using System;
class Calculator
{
// Method with parameters and a return value
public int Add(int number1, int number2)
{
int result = number1 + number2; // Method body
return result; // Return the calculated result
}
// Example of a static method to print a line of numbers
public static void PrintLine(int start, int end)
{
for (int i = start; i <= end; i++)
{
Console.Write(i + " ");
}
Console.WriteLine(); // New line for better formatting
}
}
class Program
{
static void Main(string[] args)
{
Calculator calc = new Calculator(); // Create an object to call instance methods
int sum = calc.Add(5, 10); // Call the Add method and store the result
Console.WriteLine("Sum: " + sum); // Output: Sum: 15
Calculator.PrintLine(0, 4); // Call the static PrintLine method
}
}
Output
Sum: 15
0 1 2 3 4
Method Invocation (Calling Methods)
Invoking or calling a method allows you to run the code inside its body. Usually, to accomplish this, the method’s name is written after parentheses () and a semicolon (;). Parentheses are used to pass the arguments (values) if the method calls for them.
Code Example: Simple Method Call
using System;
class Program
{
// Method declaration
static void PrintGreeting()
{
Console.WriteLine("Hello from the Govindhtech Solutions!");
}
static void Main(string[] args)
{
PrintGreeting(); // Method invocation (calling the method)
}
}
Output
Hello from the Govindhtech Solutions!
Method Overloading
When several methods have the same name but distinct argument lists inside the same class (or even in child classes), this is known as method overloading. This enables methods to handle different types of data or amounts of arguments while still performing comparable tasks. Depending on the arguments supplied during the method invocation, the compiler chooses which overloaded method to call. It is also possible to overload constructors.
Code Example: Method Overloading
using System;
class AreaCalculator
{
// Method to calculate area of a square
public double CalculateArea(double side)
{
return side * side;
}
// Overloaded method to calculate area of a rectangle
public double CalculateArea(double length, double width)
{
return length * width;
}
// Overloaded method to display an integer
public void Display(int value)
{
Console.WriteLine("Integer value: " + value);
}
// Overloaded method to display a string
public void Display(string message)
{
Console.WriteLine("String message: " + message);
}
}
class Program
{
static void Main(string[] args)
{
AreaCalculator calculator = new AreaCalculator();
double squareArea = calculator.CalculateArea(5.0);
Console.WriteLine("Area of square: " + squareArea);
double rectangleArea = calculator.CalculateArea(4.0, 6.0);
Console.WriteLine("Area of rectangle: " + rectangleArea);
calculator.Display(123); // Calls Display(int)
calculator.Display("Hello Overloading!"); // Calls Display(string)
}
}
Output
Area of square: 25
Area of rectangle: 24
Integer value: 123
String message: Hello Overloading!
Other Related Concepts
Method Overriding: This idea entails a derived class offering a fresh implementation of a base class method that already exists. Only parent and child classes can do this, and the derived class usually has to override the virtual keyword in the base class. As a result, the derived class’s method behaves differently.
Method Hiding (Shadowing): Additionally, C#’s new keyword enables a derived class to conceal a base class method. Effectively “shadowing” the base class method, this adds a new method to the derived class that is separate from it.
Abstract Methods: A defined method that lacks an implementation (body) is called an abstract method. A semicolon must be used to end it, and it only offers a declaration or signature. It is necessary to designate the class as abstract if it has an abstract method. All inherited abstract methods must have an implementation (override) provided by any non-abstract subclass, and abstract classes cannot be created.
Best Practices for Methods
It is advised to follow specific guidelines for methods while writing C# code of the highest calibre:
Single Responsibility: Every approach ought to carry out a single, clear-cut task. Multiple, unconnected tasks shouldn’t be attempted to be solved by a method.
Descriptive Naming: Beginning with a capital letter and adhering to the PascalCase convention, method names should appropriately convey their function (e.g., SendEmail(), CalculateArea()). Ideally, a word or verb-noun combination that describes an action should be included in names.
Error Handling: If an erroneous input or situation prevents a method from completing its work, it should either communicate an error (for example, by throwing an appropriate exception) or successfully complete the task as described. Methods should never provide inaccurate or deceptive findings.
Low Dependency: To encourage reuse and maintainability, methods should depend as little as possible on classes or methods that are outside of their immediate scope.
Conciseness: To make complex methods more readable and structured, they can be divided into smaller, conceptually distinct sub-methods.
Documentation: Class, constructor, method, argument, return value, and exception descriptions should all be included in XML documentation comments that begin with ///. This aids in producing technical documentation for the program.
You can alos read What Are Loops In C# With examples & Loop Control Statements