Search code examples
c#access-modifierscode-sharing

Can `internal` access modifier be used to split a class over multiple files?


The topic I'm currently in is code sharing. It is suggested that using the access modifier internal for sharing code between multiple files is possible. But is it? Or do I got it wrong? I can't post the link, because the source is not accessible for everyone.

Is it possible to have the definition of a class in one file (like an interface, or abstract class) and have the implementation of it in another file (and using internal here)?

Here is some pseudo code (obviously not working). Definition in one file:

internal static class SongLoader
{
    internal async static Task<IEnumerable<Song>> Load();
    internal async static Task<Stream> OpenData();
}

Implementation in another file:

internal static class SongLoader
{
    internal const string Filename = "songs.json";

    internal static async Task<IEnumerable<Song>> Load()
    {
        // implementation
    }

    internal static Stream OpenData()
    {
        // implemenation
    }
}

Or is it possible to have Load() defined in one file and OpenData() in another, while using internal access modifier? Is this possible? How?


Solution

  • internal specifier is used to restrict the class/members being used in other than the containing assembly.

    Code sharing is achieved via partial classes. You can have part of a class in one file and the other part in another file.

    In File A

    public partial class MyClass
    {
      public void Foo()
      {
      }
    }
    

    In File B

    public partial class MyClass
    {
      public void Bar()
      {
      }
    }
    

    You cannot have declaration in one file and definition in one file as in C++. If you have such requirements, you should think about interface or abstract classes.