Jump to content
  • Advertisement
Sign in to follow this  
Armigus2

Can you cast using a Type variable?

This topic is 2486 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

The use case is fairly basic. It is based on XNA's Content Manager but could easily be applied elsewhere.

Dictionary<string, Type> loadMap = new Dictionary<string, Type>();
Dictionary<string, object> loadedAssets = new Dictionary<string, object>();

loadMap.Add("Texture", typeof(Texture2D));
loadMap.Add("Effect", typeof(Effect));
loadMap.Add("Music", typeof(Song));
loadMap.Add("Sound", typeof(SoundEffect));

public dynamic Get(string type, string name)
{
if (!loadedAssets.ContainsKey(name))
loadedAssets.Add(name, ReadAsset<loadMap[type]>(name, RecordDisposableAsset));
}


C# 4 doesn't support variables as generic parameters, so this code fails. Is there another way of deferring types to allow such a dictionary to be filled by objects that can be referred to by type later?

Share this post


Link to post
Share on other sites
Advertisement
There is no good way. You can use reflection to instantiate the generic with a type variable, but it's slow and awkward; plus you can't do much since the variable declaration needs the type info to do useful stuff with it.

You might be able to change ReadAsset to not be generic, or adapt the type into method calls...

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!