Part IICreational Patterns

Creational Patterns

In a “managed” language such as C#, the process of creating a new object is simple: just new it up and forget about it. Well, there’s stackalloc, but we’re mainly talking about objects that need to persist. Now, with the proliferation of dependency injection, another question is whether creating objects manually is still acceptable, or should we instead defer the creation of all key aspects of our infrastructure to specialized constructs such as factories (more on them in just a moment!) or Inversion of Control containers?

Whichever option you choose, creation of objects can still be a chore, especially if the construction process is complicated or needs to abide by special rules. So that’s where Creational patterns come in: they are common approaches related to the creation of objects.

Just in case you’re rusty on the ways an object can be constructed in C#, let’s recap the main approaches:
  • Invocation of new creates an object on the managed heap. The object doesn’t need to be destroyed explicitly because the Garbage Collector (GC) will take care of it for us.

  • Stack allocation with stackalloc allocates memory on the stack rather than the heap. Stack-allocated objects only exist in the scope they were created and get cleaned up auto when they go out of scope. This construct can only be used with value types.

  • You can allocate unmanaged (native) memory with Marshal.AllocHGlobal and Co-TaskMemAlloc and must explicitly free it with Marshal.FreeHGlobal and CoTaskMem-Free. This is primarily needed for interoperation with unmanaged code.

Needless to say, some managed component might be working with unmanaged memory behind the scenes. This is one of the main reasons for the existence of the IDisposable interface. This interface has a single method, Dispose(), that can contain cleanup logic. If you are working with an object that implements IDisposable, it might make sense to wrap its use in a using statement (we now also have using var) so that its cleanup code gets executed as soon as the object is no longer needed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.24.134