C# Extension Methods only visible and accessible within one class ("private")

.net, c#, extension-methods

Solution

Extension methods can only be defined in a static non-generic outer (non-nested) class.

What I usually do in such scenarios is make a separate static internal class in a different namespace in the same file, then include that namespace only in that file.

It would still be visible to other classes in that assembly; the only way to avoid that is to move the consuming class (`class A` in your example) to its own assembly, which you probably don't want to do.

Problem

Is it possible, in C#, to create extension methods on a class but restrict visibility/accessibility within a class? (e.g. Extension Method A on class M is only accessible within class Z) Example: ``` class A { String foo = ""; String bar = foo.MakeMillionaire("arg"); } ``` In above example I want the extension method "MakeMillionaire" extending the String class only to be visible and accessible within class A. Can I do this somehow by defining the extension method in a static class within class A? Edit: Trying a regular nested class yields "Error: Extension methods must be defined in a top level static class".

Original source