Avoiding loitering when implementing generic data structure in C#

Viewed 62

Suppose that I have a data structure (let's say a stack) that uses an array to store the elements.

Something like this

class Stack<T>
{
    private T[] _items;
    int Size {get; set; }
    // irrelevant code
    
    T pop()
    {
         // Some condition checking
         --Size;
         T result = _items[Size];
         _items[Size] = null;         // Needed if T is a reference type and we want to reclaim the                    
                                      // memory, however will not 
                                      // compile, since T is not necessarily a reference type
        
         return result;
     }
     // Irrelevant
 }

My question, whether it is possible to make _items[Size] = null, conditional, depending on the type of T. If yes, how is it done?

1 Answers
_items[Size] = default(T);

Should work for all types, whether it's reference or value types.

Related