简体   繁体   中英

Should I be using “internal” or “private” instead of “public” for methods that call other methods?

In my C# project I have methods that call other methods like this:

options = ReferenceUtilities.GetMenuStatuses();

In my ReferenceUtilities I have coded:

   internal static SelectList GetMenuStatuses()
    {
        throw new NotImplementedException();
    }

But should I be using internal or private? I am not sure of the difference here.

As people have already answered, internal means that the member can be accesed by other code in the same assembly. private means that it can be accessed from other code in the same class.

However, one important point to add: In Properties/Assemblyinfo.cs, you can add the [assembly: InternalsVisibleTo("something")] statement, that lets you access the internal methods from a different assembly.

This can be extremely useful for unit testing purposes, and is a good reason to sometimes use internal over private.

(There is a huge debate over unit testing internals or not, but it is good to know about the possibility.)

internal means that the member can be accesed by other code in the same assembly. private means that it can be accessed from other code in the same class.

This has nothing to do with whether the method calls other methods.

internal is between assemblies while private is between classes

  • internal: not visible to code from other assemblies, only visible in this assembly
  • private: not visible to other classes. only visible in this class
  • public: visible to other classes or assemblies [for class]

Internal means that other classes in the same assembly can see the method. Private means only the class where the method is defined can see it. If the method will only ever be called by the class that defines it, use private. Otherwise, use internal. Public should only be used when classes outside the assembly need to call the method directly.

As always, there are exceptions, but this is a good general rule to live by.

Going a bit further, service classes (ie methods that exist solely to provide a service or feature) should implement interfaces that define the contract for that service or feature. Other classes should pass around an instance of that interface so that only the interface methods are available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM