Does C # .NET have an auxiliary highlighting class similar to mine?

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

+6
source share
2 answers

Looks like you're looking for a Lazy <T> Class .

Lazy Class

Provides support for lazy initialization.

Lazy initialization occurs on first access to the Lazy <T> .Value resource

+15
source
+6
source

Source: https://habr.com/ru/post/887870/


All Articles