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.
Asked
Active
Viewed 94 times
1

Alexey
- 1,354
- 13
- 30
-
What's the problem? Why do you think it's an anti-pattern? – Marius Bancila May 22 '15 at 06:20
-
I've never seen `new X` not create an X. The only thing I've heard about that might come close is [MS Fakes](http://stackoverflow.com/questions/9677445/mock-framework-vs-ms-fakes-frameworks). I'd not use this outside of testing. – user2864740 May 22 '15 at 06:21
-
@user28 there are some small exceptions... `new string(new char[0])` will return the `string.Empty` singleton... but they are rare exceptions handled by the CLR. – xanatos May 22 '15 at 07:24
-
Sounds like a [Singleton pattern](http://csharpindepth.com/Articles/General/Singleton.aspx) to me. But instead of a Property `Instance` for C# you can make a method `Create()` that returns the Instance. – Kevin Cruijssen Jun 24 '15 at 12:20
1 Answers
0
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()