Please read my follow-up post after reading this one.
Quoth rjw on stackoverflow…
Given the following client code:
var obj = new Class1();Is there any way to modify the constructor of Class1 so that it will actually return a subclass (or some other alternate implementation) instead?
C# compiler guru, Eric Lippert commented…
We are considering adding a feature “extension new” which would essentially allow you to make a static factory method that would be called when the “new” operator is used, much as extension methods are called when the “.” operator is used. It would be a nice syntactic sugar for the factory. If you have a really awesome scenario where this sort of pattern would be useful, I’d love to see an example.
I have one!
Version one of our DLL had a class that wrapped a connection to a remote server.
using (var connect = new ExampleConnection("service.example.com")) { connect.DoStuff(42); }
It worked great. Our customers were very happy with it and developed lots of code to use our little DLL. Life was good.
Time passes and our customers ask us to add support for a different type of server that does a similar job but with a very different protocol. No problem, we develop a new class called DifferentConnection and just to be helpful, both ExampleConnection and DifferentConnection implement a common interface object.
We’re about to release version two to our customers, but a common response comes back;
“This is good, but we were hoping your library would automatically detect which variety of server it’s talking to. Also, we really don’t want to change our code. We want to just drop your updated DLL into the install folder, but we’ll recompile our EXE if we really have to.”
With these new requirements, ExampleConnection had to become a class that supported both varieties of remote server. The constructor has to perform the auto-detect, and all of the public functions now all begin with an if statement, selecting for which variety of remote server is in use.
If we had a bit more foresight, we should have supplied a static Connect function that wrapped a private constructor. That way, version two of this function could have returned a subclass object instead. But we didn’t. There are costs to writing code that way, so you wouldn’t do it unless there was a clear point to it. If a normal constructor could return a subclass instead, there would be no problem.
Mr Lippert, I hope this provides the justification you need to add this to .NET 5, but I’d much rather have destructors on structs instead. I also want a pony.
Picture credit: ‘LEGO Mini Construction Site’ by flickr user ‘bucklava’.
(I don’t really want a pony.)
UPDATE: Someone submitted this to reddit. Lots of discussion there.
UPDATE(2): Follow-up post.