I implemented the following class:
public class ClassAllocator<T> where T : new() { public delegate T Allocator(); T obj; Allocator allocator = () => new T(); public ClassAllocator( T obj ) { this.obj = obj; } public ClassAllocator( T obj, Allocator allocator ) { this.obj = obj; this.allocator = allocator; } public T Instance { get { if( obj == null ) { obj = allocator(); } return obj; } } }
It seems to me that this simple and useful should be somewhere in .NET. In addition, I understand that the class I made is somewhat incorrect. The class is designed to work with objects that do not have a default constructor, but my "where" clause requires it in all cases.
Let me know if there is anything in .NET that I can use, so I can get rid of this class, since I would not want to continue to use the invented wheel.
Thanks!!!!
UPDATE:
I am using .NET 3.5. Sorry, I didn’t mention this before, I didn’t know that this was relevant until a few good answers started :)
source share