views:

178

answers:

3

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?

+4  A: 

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.

klausbyskov
hm, I'm assuming we wouldn't want to change the MyClass otherwise you could have the DoIt function as a normal function in MyClass. But then again why have the DoIt function at all if the DoItWith20 can call the PerformAction itself
ThanosPapathanasiou
@ThanosPapathanasiou MyClass could be code you don't have access to. e.g. a third party assembly
Dolbz
@ThanosPapathanasiou: I know that the example is perfect from a logic point of view, but it was what I could come up with in a hurry. However it does illustrate that private extension methods are not pointless.
klausbyskov
@Dolbz yes, I thought of that that's why I said we wouldn't (and maybe couldn't) want to change it.
ThanosPapathanasiou
@klausbyskov I guess if we had a big static class full with many useful functions ( not extensions ) then it would have meaning otherwise having extension methods call other extension methods defeats the whole purpose of making the code more robust
ThanosPapathanasiou
+1  A: 

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

Dolbz
+2  A: 

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

saret
I didn't quite get what you said the first time I read it, mostly because I tend to avoid big helper classes where a private static helper class would make sense, after some thought I think your answer is correct. +1
ThanosPapathanasiou