Extension Method with parameter in C#

Extension Method with parameter in C#

We have already explained Extension Method in C#Reflection Introduction c#Insert data into Database table using SQLBulkCopy class in C#as keyword C#, Import/Upload Excel file in asp.net with C#The Microsoft Jet database engine cannot open the file. It is already opened exclusively by another user,   Call method after specific time interval C#Alert from code behind asp.net,required field validator in asp.net,Difference between RegisterClientScriptBlock and RegisterStartupScript asp.netDifference between ref and out parameters.

Today I am going to explain regarding Extension Method with more than single parameter in C#. In Extension Method, first parameter represents instance on which you want method to act, but we could also add another parameters as well.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExtensionMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            string strInput = "extension method in c#- Technothirsty";
            string strOutPut = strInput.strFirstLatterUpper(" Technical website");
            Console.WriteLine("Input String  : " + strInput);
            Console.WriteLine("Output String : " + strOutPut);
            Console.ReadKey();
        }
    }

    public static class MyExtensionClass
    {
        public static string strFirstLatterUpper(this string strVal, string strAppend)
        {
            if (strVal.Length > 0)
            {
                char[] array = strVal.ToCharArray();
                array[0] = char.ToUpper(array[0]);
                return String.Concat(new string(array), strAppend);
            }
            return strVal + strAppend;
        }
    }
}

OUTPUT:

Extension Method With Parameter Output
Extension Method With Parameter Output

As you can check that while we will access that Extension method, in Intellisense you will find single parameter as shown below:

Extension Method with parameter in C#
Extension Method with parameter in C#

Thanks and please share you views with us as well.

* Difference between a regular static method and an extension method is that the first parameter of the extension method specifies the type that it is going to operator on, preceded by the this keyword.

* Extension methods can be used anywhere in the application by including the namespace of the extension method

Leave a Reply