All About Methods in C#

Introduction

Programming has evolved from assembly language to OOP. And in every language we have some common concepts, like functions (also called methods). Alternatively they can be called a procedure or a sub-routine.

All do the same to some extent.

In C#, they are ususlly called methods rather than functions. Since it belongs to the OOP family, it has various behaviors and properties.

The following are the contents of this article:

  • Static methods
  • Parameterized method that return value
  • Reference and Value Type Parameter
  • Out Parameter
  • Params keyword

Illustration

  1. Static Methods

    Static methods belong to a class rather than their objects or instance. A static member is never initialized when you are initialize the class to create the object. Sinice there is only a copy of the members that belongs to the class.

    We generally have static methods in Console applications. That is because we have a default main() method and that is a static member. You can't call a non-static member from a static class. You need to create a static method to get called from main() method.
     
    1. class Program  
    2. {  
    3.         static void ShowMessage()  
    4.         {  
    5.             Console.WriteLine("WOW !! I 'm in ShowMessage()");  
    6.         }   
    7.         static void Main(string[] args)  
    8.         {  
    9.             Console.WriteLine("I 'm INSIDE main() ");  
    10.             ShowMessage();  
    11.             Console.ReadKey();  
    12.         }  

    Here, we have both methods as static. Since you are bound to call have ShowMethod() as static.

    Note: A static member can call only call those members that are static.

  2. Parameterized Method that return some value

    We have a method that has its own block. And, to make your method productive, you need an input value for your method.

    The values that are ed to the method are known as parameters (or arguments).

    Analogous Example

    Consider a Biscuit Machine that takes Wheat, Sugar and sweat essence as raw material.

    Further, it produces biscuits as the final product.

    With this context, you can say that a Biscuit Machine is a method and the raw materials are the input parameters.

    And, your final biscuit is the returned value that we will deal with in the next paragraph.
     
    1. class Program  
    2. {  
    3.         static void ShowMessage()  
    4.         {  
    5.             Console.WriteLine("WOW !! I 'm in ShowMessage()");  
    6.         }   
    7.         static void Main(string[] args)  
    8.         {  
    9.             Console.WriteLine("I 'm INSIDE main() ");  
    10.             ShowMessage();  
    11.             Console.ReadKey();  
    12.         }  

    In this code, we ed two values (string and integer) as parameters to the HelloMessage() method. And inside that method we have a print statement that prints a simple greeting message using those parameters.

    Now, let's put a method that actually returns a value.

    1. class Program  
    2. {  
    3.         static string CanIVote(int age)  
    4.         {  
    5.             if (age < 18)  
    6.                 return "No, You Can't Vote. :'( ";  
    7.             else  
    8.                 return "Yes, You can Vote buddy :) ";          
    9.         }  
    10.         static void Main(string[] args)  
    11.         {   
    12.             Console.WriteLine("Give Your Name :");  
    13.             string name = Console.ReadLine();   
    14.             Console.WriteLine("Your Age, please ");  
    15.             int age = Convert.ToInt32(Console.ReadLine());   
    16.             string status = CanIVote(age);  
    17.             Console.WriteLine("Dear "+name+",\n "+status);  
    18.             Console.ReadKey();  
    19.       }  

    In this listing we tried to get a string type return value by checking a simple condition. If the condition is satisfied then the method will return “No, you can't vote” else “Yes, you can vote”.

    And that returned value is stored in that variable that is assigned with the calling method, in other words status.

  3. Reference Type and Value Type Parameter

    Until now, we have ed our parameter without any consideration. But, unknowingly we have ed out parameter as a value type.

    Parameters are of two types
     
        1. Reference Type
        2. Value Type

    Yes, there is a difference between the two, but we rarely care about the reference type variable.

    First, we will try with a value type:
     
    1. class Program  
    2. {  
    3.         static string CanIVote(int age)  
    4.         {  
    5.             if (age < 18)  
    6.                 return "No, You Can't Vote. :'( ";  
    7.             else  
    8.                 return "Yes, You can Vote buddy :) ";          
    9.         }  
    10.         static void Main(string[] args)  
    11.         {   
    12.             Console.WriteLine("Give Your Name :");  
    13.             string name = Console.ReadLine();   
    14.             Console.WriteLine("Your Age, please ");  
    15.             int age = Convert.ToInt32(Console.ReadLine());   
    16.             string status = CanIVote(age);  
    17.             Console.WriteLine("Dear "+name+",\n "+status);  
    18.             Console.ReadKey();  
    19.       }  

    So, the output of this type is:

    Reference Type and Value Type

    And, when we try with a reference type:

    1. class Program  
    2. {  
    3.         static string CanIVote(int age)  
    4.         {  
    5.             if (age < 18)  
    6.                 return "No, You Can't Vote. :'( ";  
    7.             else  
    8.                 return "Yes, You can Vote buddy :) ";          
    9.         }  
    10.         static void Main(string[] args)  
    11.         {   
    12.             Console.WriteLine("Give Your Name :");  
    13.             string name = Console.ReadLine();   
    14.             Console.WriteLine("Your Age, please ");  
    15.             int age = Convert.ToInt32(Console.ReadLine());   
    16.             string status = CanIVote(age);  
    17.             Console.WriteLine("Dear "+name+",\n "+status);  
    18.             Console.ReadKey();  
    19.       }  

    And the output will be:

    Reference Type

    So, there is a big difference between these two.

    In a value type, we have done the same thing as is done in a reference type. Then, what is the difference?

    Both the value type and reference type treat their variable differently. In a value type, we get a copy of the variable's value but in a reference type we get the actual variable address.

    So, whatever changes you make in the reference type remains there. But the changes don't affect the value type because their scope of the actual variable and the copy of the variable are different.

    Here, we use the ref keyword to denote a reference type variable (& is used in the C++ Language to specify a reference variable).

  4. Out Parameter

    One of the limitations of a method is that they can't return multiple values at a time.

    For that, the C language has pointers. You know very well, that pointers are not an easy game to play with. That's why most languages avoid that concept, as does C++ and C#.

    But, C# has the out keyword to solve this problem in its own way.

    Let's have a small peice of code showing that:
     
    1. class Program  
    2. {  
    3.         static string CanIVote(int age)  
    4.         {  
    5.             if (age < 18)  
    6.                 return "No, You Can't Vote. :'( ";  
    7.             else  
    8.                 return "Yes, You can Vote buddy :) ";          
    9.         }  
    10.         static void Main(string[] args)  
    11.         {   
    12.             Console.WriteLine("Give Your Name :");  
    13.             string name = Console.ReadLine();   
    14.             Console.WriteLine("Your Age, please ");  
    15.             int age = Convert.ToInt32(Console.ReadLine());   
    16.             string status = CanIVote(age);  
    17.             Console.WriteLine("Dear "+name+",\n "+status);  
    18.             Console.ReadKey();  
    19.       }  

    The output will be:

    Out Parameter

    Here, without returning any value we have returned more than one value.

    And, it's because of out.

    We can treat an out variable as a commonly shared variable between the calling and called block.

    In other words, these add, diff, mul and div variables are common variables between the main() and Calculation() blocks.

  5. Params Keyword

    If you are not sure about the actual number of parameters then you can use the params keyword.

    Because it allows you to specify any number of parameters for a method.
     
    1. class Program  
    2. {  
    3.         static string CanIVote(int age)  
    4.         {  
    5.             if (age < 18)  
    6.                 return "No, You Can't Vote. :'( ";  
    7.             else  
    8.                 return "Yes, You can Vote buddy :) ";          
    9.         }  
    10.         static void Main(string[] args)  
    11.         {   
    12.             Console.WriteLine("Give Your Name :");  
    13.             string name = Console.ReadLine();   
    14.             Console.WriteLine("Your Age, please ");  
    15.             int age = Convert.ToInt32(Console.ReadLine());   
    16.             string status = CanIVote(age);  
    17.             Console.WriteLine("Dear "+name+",\n "+status);  
    18.             Console.ReadKey();  
    19.       }  

    The output is:

    Params Keyword

    In this code, first we ed 7 integer arguments and in the second we ed 3 arguments.

    And, the called method treats it as an integer array.

    So, whenever you are not sure about the actual number of parameters, use params without any thought.

Conclusion

We have explained methods and their few unsung features.

Next, you can move to Polymorphism to get more about methods.


Recommended Free Ebook
Similar Articles