I am a big fan of the XML documentation comments in C#. This documentation is directly in the code and has therefore the biggest chance to be updated when the code changes.
However, when you demand to document all public methods, you end up with a lot of repetitive documentation. As with duplicated code, you will update only the parts you remember, and the others will be outdated in no time. That quickly negates the benefits of having the documentation in the first place.
A simple solution for this problem is to inherit the documentation that should be the same. We can do that with the keyword inheritdoc.
This keyword allows us to document the interface with all the necessary details only once and then inherit this documentation in our implementations:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
/// <summary> /// The contract a user repository implementation /// must follow /// </summary> public interface IUserRepository { /// <summary> /// Add a user to the repository /// </summary> /// <param name="user">the user you want to add</param> /// <returns>the generated Id</returns> int Add(User user); /// <summary> /// Returns the user for the given Id /// </summary> /// <param name="id">the Id you want</param> /// <returns>the matching user</returns> User FindById(int id); /// <summary> /// Updates a user and sets its values to the ones /// provided in the object /// </summary> /// <param name="user">object with the new values</param> void Update(User user); } |
In the class that implements our interface we only need to document what makes this implementation special while we reuse the documentation for the methods:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
/// <summary> /// This repository implementation lets you store /// your users in a SQL Server database. /// </summary> public class DbUserRepository : IUserRepository { /// <inheritdoc cref="IUserRepository.Add"/> public int Add(User user) { ... } /// <inheritdoc cref="IUserRepository.FindById"/> public User FindById(int id) { ... } /// <inheritdoc cref="IUserRepository.Update"/> public void Update(User user) { ... } } |
Not only do you need to write less documentation, if things change, we only need to update it at one place. In Visual Studio everything looks as if we wrote the documentation on the class itself:
Wherever we used this approach, the developers stopped to bother writing slightly varying comments for the different implementations. Instead, that time was used to think a bit more about the documentation of the interface, what leads to more useful descriptions. Try it!
I have tried doing this and the comment does not show up when I hover, is there a setting required to turn it on?
Hi Issun,
It may be a ReSharper feature that is not present in the basic Visual Studio edition.
Regards,
Johnny
When I use inheritdoc, I don’t know why, but it doesn’t show me the “param” documentation.
Any idea why?