Jaroslav Kubacek
Jaroslav Kubacek

Reputation: 1447

C# Generic contains Generic

Is a way to change where constraint for generic class containing generic member to avoid constructions like this:

var _queue = new CommunicationQueue<DataTag<Messages>, Messages>(10);
//this is what I would like:
//var _queue = new CommunicationQueue<DataTag<Messages>>(10);

public class CommunicationQueue<TU, T> where TU : DataTag<T>, new()
                                       where T : struct
{
   private readonly ConcurrentQueue<TU> _queue;
   public int Limit { get; }

   public CommunicationQueue(int queueSize)
   {
       Limit = queueSize;
       _queue = new ConcurrentQueue<TU>();
   }

   internal void AddItem(T item)
   {
      _queue.Enqueue(new TU { RowData = item });
       while (_queue.Count > Limit)
       {
          TU removed;
          _queue.TryDequeue(out removed);
       }
   }

   public IEnumerable<TU> GetLatestItems()
   {
      return _queue.Reverse().Take(Limit).ToArray();
   }
}

 public class DataTag<T> where T : struct 
 {
     public DateTime Time { get; set; }   

     public T RowData { get; set;}

     public DataTag()
     {
         Time = DateTime.Now;
     }

     public DataTag(T rowData) : this()
     {
         RowData = rowData;
     }
 }

public struct Messages
{
    string Name { get; set; }
    ...
}

Now to create a queue I should write:

var _queue = new CommunicationQueue<DataTag<Messages>, Messages>(10);

But this is what I would like:

var _queue = new CommunicationQueue<DataTag<Messages>>(10);

Upvotes: 1

Views: 113

Answers (1)

Colin Grealy
Colin Grealy

Reputation: 615

First of all, are you planning to inherit from DataTag<T>?

If not, then you could change the definition of CommunicationQueue to

public class CommunicationQueue<T> 
    where T : struct
{
   private readonly ConcurrentQueue<DataTag<T>> _queue;
//....
}

Upvotes: 2

Related Questions