Search code examples
c#.netextension-methodsgeneric-programming

C# Extending generic method


Good day,

Is there a way to extend generic method? for example

i have such method:

public T DoSomethingAboutIt<T>()
{
//do magic
}

what i want to is to have extended method such as:

private static T Extended<T, L>(this T o, Func<T, L> func)
{
    return default(T);
}

Is this extension is possible?

edit: i would like to call it like this something DoSomethingAboutIt().Extended...


Solution

  • It's possible but you still have to follow the rules of Extension Methods (MSDN).

    This code compiles just fine...

    internal class Program
    {
        private static void Main(string[] args)
        {
            int y = 1;
            int z = y.Extended(n => "hi!");
        }
    }
    
    public static class X
    {
        public static T Extended<T, L>(this T o, Func<T, L> func)
        {
            return default(T);
        }
    }