Methods in C#
Methods sometimes referred to as functions, offer a powerful tool for encapsulating logic within your code, enabling you to define it once and apply it across various sections of your application. This practice greatly simplifies the maintenance of your application. In cases where you don't require a method to return a value, you can specify its return type as "void."
Static and Instance Methods
Static Method - A method is classified as static when its declaration includes the "static" modifier. Static methods are invoked using the class name, and only a single definition of the static method exists because there are no instances of this method when it's marked as static.
Instance Method - Conversely, when a method declaration lacks the "static" modifier, it is termed an instance method. You can create multiple instances of the class, and each instance has its own independent copy of the method, making it unique to that specific instance.
using System
class Program {
// this method is called a static method
public static void Main(){
Program p = new Program()
p.EvenNumbers()
}
// this method is called an instance method
public void EvenNumbers(){
int Start = 0;
for (i= 0 ; i < Start.length; i++){
Console.WriteLine("These are the even numbers, {0}", i)
}
}
}
// if the method is a static method , we call it as a method
// on the name of the class
using System
class Program {
// this method is called a static method
public static void Main(){
Program.EvenNumbers()
}
// this method is called an instance method
public static void EvenNumbers(){
int Start = 0;
for (i= 0 ; i < Start.length; i++){
Console.WriteLine("These are the even numbers, {0}", i)
}
}
}
adding parameters
// if the method is a static method , we call it as a method
// on the name of the class
using System
class Program {
// this method is called a static method
public static void Main(){
Program.EvenNumbers(30)
}
// this method is called an instance method
public static void EvenNumbers(int Target){
int Start = 0;
for (i= 0 ; i < Start.length; i++){
Console.WriteLine("These are the even numbers, {0}", i)
}
}
}
;.
Subscribe to my newsletter
Read articles from Joseph Lamptey directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Joseph Lamptey
Joseph Lamptey
I am Joseph Nii Lante Lamptey, a Full-stack software developer. I love learning new cool tech and I am always on a journey into the world of building cool tools for the benefit of the open-source community. I love to express my love for my favourite tools in my writing, join me on this wonderful journey as we learn together. I love meeting cool people and talking about life and all the cool things. Cheers 🥂