Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Generic methods in C#

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 197
    Comment on it

    Generic is a feature provided in C# which allows defining the class, method etc without binding it to work with a specific data type, instead it is created with a substituted type which get replaced with the data type passed at run time. In other words, generics gives advantage of writing a class or method that can work with any data type.

     

    Before we proceed, let's see an example.

     

    In the following code snippet, we want to sort arrays of different data type using a single Sort method in First and Second call. Now as the process of sorting the arrays is almost same, so in first assumption both calls in the following code snippet should work fine.

     

    Problem:

    using System;
    
    namespace ConsoleApplication1
    {
    	class Program
    	{
    		static void Main(string[] args)
    		{
    			// First Call:
    			// Passing string array to Sort method
    			var stringArray = Sort(new string[] { "orange", "grape", "strawberry", "banana", "mangoe" });
    
    			// Second Call:
    			// Passing char array to Sort method
    			var charArray = Sort(new char[] { 'j', 'u', 'd', 'i' });           // this line will throw compile time error
    
    			// Pause the window until press a key
    			Console.ReadKey();
    		}
    
    		/// <summary>
    		/// Sorts the given array in ascending order
    		/// </summary>
    		/// <param name="inputArray">String array to be sorted</param>
    		/// <returns>Sorted string array</returns>
    		static string[] Sort(string[] inputArray)
    		{
    			Array.Sort(inputArray, StringComparer.InvariantCulture);
    			return inputArray;
    		}
    	}
    }
    

     

    Compile this code and you'll see the following error.

    Error    CS1503    Argument 1: cannot convert from 'char[]' to 'string[]'

     

    Taking a close look at the error message we'll see that in process of reusing the same function for both calls, problem lies in the second call where we are trying to pass a char type of array (char[]) to the Sort method which is expecting that parameter to be of string array (string[]). As obvious these two types are not compatible with each other because of the data they are designed to be contained.

     

    On giving a second thought to this problem, one easy solution will be to add another Sort method as follows, which will be receiving a parameter of char array (char[]) type.

     

    Improper Solution:

    /// <summary>
    /// Sorts the given array in ascending order
    /// </summary>
    /// <param name="inputArray">Char array to be sorted</param>
    /// <returns>Sorted char array</returns>
    static char[] Sort(char[] inputArray)
    {
    	Array.Sort(inputArray, StringComparer.InvariantCulture);
    	return inputArray;
    }
    

     

    Well adding another Sort function isn't an overhead as long as we have only one or two types of arrays to be sorted, but this will become repetitive and unnecessary to introduce a new Sort method for sorting every new type of array.

     

    One of the best solution for this kind of situation will be to use a generic Sort method which is not bound to any specific type of parameter and can receive the parameter at the time of calling.

     

    Right Solution:

    using System;
    
    namespace ConsoleApplication1
    {
    	class Program
    	{
    		static void Main(string[] args)
    		{
    			// First Call:
    			// Passing string array to Sort method
    			var stringArray = Sort<string>(new string[] { "orange", "grape", "strawberry", "banana", "mangoe" });
    
    			// Second Call:
    			// Passing char array to Sort method
    			var charArray = Sort<char>(new char[] { 'j', 'u', 'd', 'i' });
    
    			// Third Call:
    			// Passing double array to Sort method
    			var doubleArray = Sort<double>(new double[] { 4, 6, 0, 2, 8 });     // Extra call added to sort the double array
    
    			// Pause the window until press a key
    			Console.ReadKey();
    		}
    
    		/// <summary>
    		/// Generic method to sort an array
    		/// </summary>
    		/// <typeparam name="T">T will be assigned the data type passed at the time of calling</typeparam>
    		/// <param name="inputArray">Array to be sorted</param>
    		/// <returns></returns>
    		static T[] Sort<T>(T[] inputArray)
    		{
    			Array.Sort(inputArray, StringComparer.InvariantCulture);
    			return inputArray;
    		}
    	}
    }
    

     

    In the above Sort method we haven't used any data type as earlier, instead we have used T which will get substituted with the data type passed at the time of function call. Therefore in the First Call after receiving string array parameter, Sort method will assume T[] equals to string[], in Second Call Sort method will assume T[] equals to char[] and so on.

     

    In the above generic method, try to replace the following line

    static T[] Sort<T>(T[] inputArray

    with

    static T[] Sort(T[] inputArray)		// removed <T>

    and you will get an error, that's because we have actually removed the receiving parameter used for receiving the data type at the time of calling.

     

    So in this call

    Sort<string>(new string[] { "orange", "grape", "strawberry", "banana", "mangoe" });

    we can think of following assignment

    Sort<string> = Sort<T> 

     

    Conclusion:

    Here we have seen how generic methods can help us to reduce the code by keeping the repetitive functionality at one place with type as a parameter that will be initialized with the data type at the time of its calling.

     

    Every time we have a functionality in mind that is common for all the concerned data types (including user defined), we should choose generic method for the same. Also remember we can have generic interfaces, classes, methods, events and delegates as well.

     

    Hope you find it useful.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: