Search code examples
c#classpartial-classes

C# - private static method in partial class not shared between files?


I'm creating static partial class like this.

If I put them in the same file there is no problem, but when I move one class to another file in the same project, this method private_method_from_a() does not exist anymore.

Is this by design? Do I miss something here?

    //File A
    public static partial class PartialClass
    {
        private static void private_method_from_a()
        {
            //Do something
        }
    }

    //File B
    public static partial class PartialClass
    {
        public static void public_method_b()
        {
            private_method_from_a();
        }
    }

Solution

  • Most likely the two files are in different namespaces, as @MickyD suggested in a comment. The reason for this problem is you're then making 2 different classes entirely. Chances are, one of them is in the namespace of your project, while the other is in the global namespace - that is, you didn't specify a namespace for it at all. Here's how the compiler sees them (suppose your project is called "MyProject", and has that name as the top-level namespace):

    partial class global::MyProject.PartialClass

    and

    partial class global::PartialClass

    Well, that's two distinct types, with different fully qualified names, both partial.

    Make sure they're are both in the same namespace for the C# compiler to treat them as the same type.