Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

class

partial

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!

like image 982
dak1220 Avatar asked Oct 17 '25 14:10

dak1220


1 Answers

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.

like image 152
Willem Van Onsem Avatar answered Oct 19 '25 04:10

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!