Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have you ever used private extension methods?

Is there any advantage of having the option of using private extension methods? I haven't found any use for them whatsoever. Wouldn't it be better if C# didn't allow them at all?

like image 835
Thanos Papathanasiou Avatar asked Mar 03 '10 11:03

Thanos Papathanasiou


3 Answers

This is helpful for improving the syntax of code within a method/class, but you don't want to expose the functionality offered by that extension method to other areas of the codebase. In other words as an alternative for regular private static helper methods

like image 182
saret Avatar answered Nov 17 '22 18:11

saret


Consider the following:

public class MyClass
{
    public void PerformAction(int i) { }
}

public static class MyExtensions
{
    public static void DoItWith10(this MyClass myClass)
    {
        myClass.DoIt(10);
    }

    public static void DoItWith20(this MyClass myClass)
    {
        myClass.DoIt(20);
    }

    private static void DoIt(this MyClass myClass, int i)
    {
        myClass.PerformAction(i);
    }
}

I realize that the example does not make much sense in its current form, but I'm sure you can appreciate the possibilities that private extension methods provide, namely the ability to have public extension methods that use the private extension for encapsulation or composition.

like image 24
Klaus Byskov Pedersen Avatar answered Nov 17 '22 19:11

Klaus Byskov Pedersen


I just Googled to investigate as I was doubtful that there was much use for them. This however is an excellent illustrative application for them:

http://odetocode.com/blogs/scott/archive/2009/10/05/private-extension-methods.aspx

like image 3
Dolbz Avatar answered Nov 17 '22 18:11

Dolbz