#518 – Splitting the Implementation of a Class Across Multiple Files

It is sometimes convenient to split the source code for a class across more than one source file.  You can do this using the partial keyword.

In the example below, we split the implementation of the Dog class between Dog.cs and Dog-IBark.cs.  The latter file contains the implementation of the IBark interface.  The class definition in both files is marked with the partial keyword.

    // Dog.cs
    public partial class Dog
    {
        public string Name { get; set; }
        public int Age { get; set; }

        /// <summary>
        /// Create new Dog with specified name
        /// </summary>
        /// <param name="name"></param>
        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
        }
    }

 

    partial class Dog : IBark
    {
        public bool CanBark { get; set; }

        public void Bark()
        {
            Console.WriteLine("WOOOOOF!");
        }
    }

Notice that we don’t specify IBark inheritance in the first file, because it does not implement any IBark methods.

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.