Search code examples
c#.netextension-methodsaccess-modifiersclass-visibility

Can I restrict the visibility of C# extension methods to classes in the same assembly?


Say I have these files:

MyCode.cs

namespace MyCodeNamespace
{
  public class MyClass
  {
    //OMITTED
  }

  internal static class MyExtensions
  {
    internal static void Foo(this string str)
    {
      //OMITTED
    }
  }
}

OtherCode.cs

using MyCodeNamespace;
namespace OtherCodeNamespace
{
  //OMITTED
}

The two files are part of the same assembly. Is there any way I can make Foo accessible to MyCode.cs but not to OtherCode.cs? My question is similar to this question: C# Extension Methods only visible and accessible within one class ("private") But its accepted answer isn't really what I'm looking for. I want to make an extension method that's only visible to the code I'm working on, and according to the answer to the above question, someone could still access it by adding a "using" statement. Is there a way I can create an extension method that is only visible to my code, and nowhere else, not even by another class in the same assembly?

I ask because the syntax for calling an extension method is handy and would be useful for what I'm working on (otherwise I'd just create a private method instead), but I don't want others to see it and use it from their code in case it doesn't do what they assume it does. And thanks to Visual Studio's intellisense, my extension methods are currently showing up in the list of available methods (along with the option to add the namespace they're in).


Solution

  • There is no such thing as a namespace-limited access modifier in the .NET platform. From the docs

    public : Access is not restricted.
    protected : Access is limited to the containing class or types derived from the containing class.
    Internal : Access is limited to the current assembly.
    protected internal: Access is limited to the current assembly or types derived from the containing class.
    private : Access is limited to the containing type.

    That's all you have to work with. So the answer is no.