Search code examples
c#classpartial

Variables declared in partial class not visible to second partial class declaration?


So I have two different source files:

file1.cs:

namespace namespace1 {
    public partial class Class1 {
        public partial class NestedClass {

             public int myInt{ get; set; }

        }
    }    
}

file2.cs:

namespace namespace1.Class1 {
    public partial class NestedClass {

         void doSomething() {
             Console.WriteLine(this.myInt); // class does not contain definition for myInt
         }
    } 
}

The Problem:

I am trying to access a member variable declared in the first partial class in the second. No variables I declare can be viewed from the other file.

My Attempts at a Solution:

I found this post, but it did not seem to fix my issue. I declared several test variables in each of the partial class files and nothing was visible to the other file. I tried both public and private variables, with and without setters, since the problem in that situation involved a missing setter. I thought maybe my classes were named incorrectly, so I triple checked my namespaces as well as class names and that they were both declared partial. Finaly, I have tried restarting Visual Studio as well, to no avail.

Any help would be greatly appreciated!


Solution

  • The problem is that in your first file, you have a namespace:

    namespace namespace1 {
    

    whereas in the second it is:

    namespace namespace1.Class1 {

    Since the namespaces are different, C# considers the classes to be different as well: they happen to have the same name, but since these are declared in separate namespaces, C# considers them to be different.

    In the case you work with partial nested classes, you should write it like:

    file1.cs:

    namespace namespace1 {
    
        public partial class Class1 {
    
            public partial class NestedClass {
    
                 public int myInt{ get; set; }
    
            }
        }
    }

    file2.cs:

    using System;
    
    namespace namespace1 {
    
        public partial class Class1 {
    
            public partial class NestedClass {
    
                void doSomething() {
                    Console.WriteLine(this.myInt); // class does not contain definition for myInt
                }
    
            }
    
        }
    }

    So you do not specify the outer class as a namespace, but you declare the outer class twice.