I have 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;
}
}
}
I feel like something this simple & useful should be in .NET somewhere. Also, I realize that the class I made is somewhat incorrect. The class is designed to work with objects that don't have a default constructor, yet my 'where' clause requires it in all cases.
Let me know if there is something in .NET I can use so I can get rid of this class, as I would hate to continue using a reinvented wheel.
Thanks!!!!
I'm using .NET 3.5. Sorry I didn't mention this before, I wasn't aware it was relevant until a few good answers started flowing in :)
Sounds like you're looking for the Lazy<T> Class.
Lazy<T> Class
Provides support for lazy initialization.
Lazy initialization occurs the first time the Lazy<T>.Value property is accessed
The Lazy class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With