#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.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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

  1. Pingback: #631 – Code-Generation Tools and Partial Classes « 2,000 Things You Should Know About C#

  2. Pingback: #633 – The Implementation of A Partial Method Is Optional « 2,000 Things You Should Know About C#

  3. Pingback: #634 – Invoking Partial Methods That Have No Implementation « 2,000 Things You Should Know About C#

  4. Pingback: #636 – The Reason for Partial Methods « 2,000 Things You Should Know About C#

  5. Pingback: #638 – Defining and Using a Partial struct « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: