Do you like to have fluent interfaces in your code because they make it more readable?
Do you have a ‘deep’ class hierarchy and you’d like to have a fluent interface without the need of always returning the base class type? and possibly avoid all the cast(s) in the methods’ chain?
Here’s the standard way of approaching Fluent Interfaces with inherited classes in C#:
As you can see it just doesn’t work out of the box! You can overcome the issue using extension methods, here’s how:
The trick is returning the same instance passed in as the ‘this’ argument in the extension method (instead of using the return value of the internal object method, which will return the wrong base type); that will have the correct type to let you go on with the method chaining.
Surely defining the api in this way is not that pretty, but that will be hidden inside your library and the users will be happy!