Replacing a constructor call with a factory method call by using a proxy in C#

102 views Asked by At

I might be going crazy, but I swear I've seen a snippet that allows the consumers of your code to write new Foo() while something like FooProxy.Create() is called behind the scenes instead of the constructor. I've been searching and searching for it, but now I cannot find it at all. I do not plan to use this at all, since it looks like an antipattern to me, but I want to make sure I didn't dream it all up.

1

There are 1 answers

0
xanatos On BEST ANSWER

The response seems to be no.... You have only dreamed. From https://stackoverflow.com/a/14343648/613130:

Q:Create constructor(?) to retrieve object from cache or recreate if null

A: You can't create a constructor which does that. A constructor always creates a new object. Instead, create a static factory method:

Note that it is surely possible to use Fody (a tool able to modify an assembly post compilation) to create a plugin that replaces direct new Foo() to FooProxy.Create()