1

I'm to trying to create a class to deal with loading in resources (textures, sounds etc). I am trying to create it so that I can do something similar to the following:

ContentHandler contentHandler=new ContentHandler(content);
Texture2D texture=contentHandler<Texture2D>["picture"];

The problem I am having is that while I can create the indexers just fine, I don't know how to use templates with it so that I can get a specific type passed to it. I could just use a regular template function, but I'd MUCH rather use the above if it's possible. I've tried searching but I have a hard time coming up with anything.

mirhagk
  • 1,255
  • 3
  • 14
  • 28

2 Answers2

3

I suspect your question is really:

Can I write a generic indexer?

If that's the case, the answer is no. You'd have to write a method instead:

Texture2D texture = contentHandler.GetValue<Texture2D>("picture");

Also note that generics aren't templates. It's worth being very clear on that :)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Generic indexers would be crazy stuff of course. Imagine what crap you can do with them ( even generic properties ). – Felix K. Mar 13 '12 at 22:38
  • Dang I was scared it wasn't implemented. Just would be so much cleaner with a generic indexer. Thanks though, I guess I'll just use have to use methods to accomplish it. – mirhagk Mar 13 '12 at 22:43
1

I think your a looking for Generics.

Possible duplicate: Why it is not possible to define generic indexers in .NET?

Community
  • 1
  • 1
Robar
  • 1,929
  • 2
  • 30
  • 61
  • Yes this is what I am looking to use with the indexer property. The class itself can't be generic however because it's a singleton. I do not want 40 different classes for 40 different kinds of resources. I would like to make the method generic, but I can't figure out how to make a generic indexer (sorry for calling it templates, I learned C++ first) – mirhagk Mar 13 '12 at 22:39
  • As Jon Skeet already mentioned you can create a generic method. http://msdn.microsoft.com/en-us/library/twcad0zb(v=vs.80).aspx – Robar Mar 13 '12 at 22:44