Search code examples
c#partial-classes

Why can't I access a private static method in one half of a partial class from the other half?


There must be something simple that I'm missing. I have two partial classes, in two different assemblies, and I'm not able to reference a private static method in one partial class from the other partial class.

For example, in the FirstHalf assembly, I have the following class:

namespace FirstHalf 
{
    public partial class TestPartialClass
    {
        private static void PrintFoo()
        {
            Console.WriteLine("Foo");
        }
    }
}

Then, in the SecondHalf assembly, I have the following class:

namespace FirstHalf 
{
    public partial class TestPartialClass 
    {
        public static void Main(string[] args)
        {
            Console.WriteLine(PrintFoo());
        }
    }
}

However, when I try to invoke PrintFoo() from the SecondHalf assembly, I get the following error:

CS0103: The name 'PrintFoo' does not exist in the current context.

What's going on, here? I have a reference from SecondHalf to FirstHalf, so Visual Studio does know that there is a dependency between the two.


Solution

  • You can't split a partial class between two assemblies; they are actually being compiled as two different classes.

    If you really want to accomplish something like this across assemblies, with sharing of 'private' members, you can get something similar by creating a base class and inheriting it:

    namespace FirstHalf
    {
        public class Base
        {
            protected static void PrintFoo()
            {
                Console.WriteLine("Foo");
            }
        }
    }
    
    namespace SecondHalf
    {
        public class Derived : FirstHalf.Base
        {
            public static void Main(string[] args)
            {
                PrintFoo();
            }
        }
    }
    

    That said, there is probably a cleaner way to accomplish what you're trying to do using some form of composition; the details depend on your particular application.