nested partial class

Pablo gil 86 Reputation points
2021-09-28T15:49:32.397+00:00

I want to define a nested class in a separate file to keep enclosing class simple,
I need a nested class cause I want it to be able to access private members of the
enclosing class. However I do not know how to set up namespaces.
Please can anybody help?

Developer technologies C#
{count} votes

Accepted answer
  1. Timon Yang-MSFT 9,606 Reputation points
    2021-09-29T07:03:15.077+00:00

    For partial classes, they must have the same fully qualified name.

    myNameSpace.MyEnclosingClass.MyNestedClass and myNameSpace.MyNestedClass are two completely unrelated classes.

    For the code example you provided, the first paragraph and the second paragraph are not allowed to exist at the same time. Even if allowed, their full names are still different.

    136211-capture.png

    If you need to use nested classes, you can add MyEnclosingClass in the third code and make it a partial class, and then put MyNestedClass in it.

    namespace myNameSpace  
    {  
        internal partial class MyEnclosingClass  
        {  
            internal partial class MyNestedClass { }  
        }  
    }  
      
    namespace myNameSpace  
    {  
        internal partial class MyEnclosingClass  
        {  
            internal partial class MyNestedClass { }  
        }  
    }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2021-09-28T16:42:08.933+00:00

    Partial classes allow breaking a class definition into multiple source files. all the source files must use the same namespace and class name. Also all source files must define the class as a partial.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.