Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have a generic this[] property?

Tags:

c#

generics

I have a DICOM dictionary that contains a set of objects all deriving from DataElement. The dictionary has an int as a key, and the DataElement as property. My DICOM dictionary contains a this[] property where I can access the DataElement, like this:

public class DicomDictionary
{
  Dictionary<int, DataElement> myElements = new Dictionary<int, DataElement>();
  .
  .
  public DataElement this[int DataElementTag]
  {
    get
    {
      return myElements[int];
    }
  }
}

A problem now is that I have different DataElement types all deriving from DataElement, like DataElementSQ, DataElementOB and so on. What I wanted to do now is the following to make writing in C# a little bit easier:

 public T this<T>[int DataElementTag] where T : DataElement
 {
   get
   {
      return myElements[int];
   }
 }

But this is not really possible. Is there something I have missed? Of course I could do it with Getter method, but it would be much nicer to have it this way.

like image 801
msedi Avatar asked Aug 12 '11 16:08

msedi


1 Answers

The best options are to either use a generic method (instead of an indexer), or to have your class be generic (in which case, the indexer would be tied to the class generic type). A generic indexer as you've described is not allowed in C#.

like image 195
Reed Copsey Avatar answered Oct 05 '22 13:10

Reed Copsey