Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C#.NET have an allocation helper class similar to mine?

Tags:

c#

.net

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!!!!

UPDATE:

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 :)

like image 244
void.pointer Avatar asked May 11 '11 19:05

void.pointer


2 Answers

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

like image 197
dtb Avatar answered Sep 19 '22 23:09

dtb


The Lazy class

like image 35
Noffls Avatar answered Sep 21 '22 23:09

Noffls