c# – How to create nested partial classes?

Question:

I have a Library class which has several nested classes:

public class Library
{
class Book { /*Some code*/ }
class Author { /*Somecode*/ }
class Series { /*Somecode*/ }
class Topic { /*Somecode*/ }
}

But there is a lot of code in one file, so I decided to move the Book, Author, Series, Topic classes into separate files. To do this, I made them partial.

public class Library
    {
    partial class Book { }
    partial class Author { }
    partial class Series { }
    partial class Topic { }
    }

//Books.cs
partial class Book { /*Some code*/ }
...

But something does not work, because parts of the partial class do not see one by one.

Answer:

A partial class can be nested within a partial or non-partial class. In the latter case, the enclosing class must have one definition. For instance,

using System;

class Library
{
    public partial class Book
    {
        public string Title { get; set; }
    }

    public partial class Book
    {
        public string Author { get; set; }
    }

    public Book book;
}

public class Test
{
    public static void Main()
    {
        Library lib = new Library 
        { 
            book = new Library.Book { Title = "A good book", Author = "me" } 
        };

        Console.WriteLine( "\"{0}\" is written by {1}", 
                          lib.book.Title, lib.book.Author );
    }
}

Console output

"A good book" is written by me

If you also want the enclosing class to be defined in different parts along with the partial nested class, then you must also declare it with the partial modifier.

For instance,

using System;

partial class Library
{
    public partial class Book
    {
        public string Title { get; set; }
    }
}

partial class Library
{
    public partial class Book
    {
        public string Author { get; set; }
    }
}

partial class Library
{
    public Book book;
}

public class Test
{
    public static void Main()
    {
        Library lib = new Library 
        { 
            book = new Library.Book { Title = "A good book", Author = "me" } 
        };

        Console.WriteLine( "\"{0}\" is written by {1}", 
                          lib.book.Title, lib.book.Author );
    }
}

The console output will be the same as shown above.

Scroll to Top