0

Is there a way to specify a type in runtime through casting a string with the types name? I hop my non-compiling code below can explain what i am trying to do. Let me know otherwise and ill try to explain it better.

var valueFromDropDownMenu = "MyClass";

List<Type.GetType(valueFromDropDownMenu)> dynamicList = 
  new List<Type.GetType(valueFromDropDownMenu) > (); 

// Code to iterate through objects and populate dynamicList 
// with all objects of correct type

What I am trying to do is to let the user choose what type of object I will process.

I am Using Unity3D which is a game dev framework and it uses a static method to load resources from files. These resources needs to be cast.

I'm trying to make a developer tool that lets the developer choose a specific type of resources to be loaded. So i need to do something like

var files = LoadAll("Path, ofType(UserSelectedType)); 

Is it possible?

TaW
  • 53,122
  • 8
  • 69
  • 111
Daarwin
  • 2,896
  • 7
  • 39
  • 69
  • 6
    Have a look [here](http://stackoverflow.com/questions/11107536/convert-string-to-type-in-c-sharp), this should answer your question. – Barry O'Kane Apr 25 '16 at 11:40
  • 1
    I know this doesn't answer your question, but would it be possible for you create an interface all these types could implement, i.e do you want to do the same operation no matter what type it actually gets? – Chris Wohlert Apr 25 '16 at 11:56
  • `List` is not going to work - but you likely don't need that. I assume you already have a list of items to search from? If so, why not use the same type - since all found objects will be of that type, or a subtype, anyway? – Pieter Witvoet Apr 25 '16 at 11:59
  • Really? I think he get the class names from the menu and wants to create new objects from those strings. (`valueFromDropDownMenu` is a string after all!) If he already has objects he could try to clone them.. – TaW Apr 25 '16 at 12:11
  • @BarryO'Kane it doesnt solve my problem cause i can use a Type type when i try to cast something. Like this dosnt work: Type myType = GetType(namespaceQualifiedTypeName); myType instance = new myType(); – Daarwin Apr 25 '16 at 12:30
  • @TaW turns out you were right - even if the code comment indicated otherwise :) – Nathan Apr 25 '16 at 13:01
  • This question is bizarre ... it's completely built in to Unity. Simply see the doco for LoadAll. Of course using Linq you can conveniently cast the ensemble. example `rawArrayOfClips = Resources.LoadAll("VO/", typeof(AudioClip) ).Cast().ToArray();` – Fattie Apr 25 '16 at 14:47

1 Answers1

1

The whole point of generics is to provide compile-time typing. Attempting to use generics in the manner you describe defeats the point.

It doesn't compile because you're attempting to mix runtime typing with compiletime typing.

Even if this did work, it would just add unnecessary overhead to using a simple List<object> which can then be queried at runtime for type information. (Note, compile-time is obviously always preferable for performance)

The code below will output a single line at the console.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication9
{
    class Program
    {
        static void Main(string[] args)
        {

            List<object> x = new List<object>();
            x.Add(new MyTypeA());
            x.Add(new MyTypeB());
            foreach (var itemsOfA in x.Where(o => o.GetType().Name == "MyTypeA"))
            {
                Console.WriteLine("Found a " + itemsOfA.GetType());
            }
        }
    }

    class MyTypeA { }
    class MyTypeB { }
}
Nathan
  • 6,095
  • 2
  • 35
  • 61
  • Thanks for your time. I think then my example is a bit bad. What i am trying to do is to let the user choose what type of object i will process. I am Using Unity3D which is a game dev framework and it uses a static method to load resources from files. These resources needs to be cast. Im trying to make a developer tool that lets the developer choose a specific type of resources to be loaded. – Daarwin Apr 25 '16 at 12:22
  • (continuing...) So i need to do something like var files = LoadAll("Path, ofType(UserSelectedType)); Is it possible? – Daarwin Apr 25 '16 at 12:24
  • 1
    @Lautaro: you may want to add that information to your question - specifically how you're getting those objects and what you intend to do with them. – Pieter Witvoet Apr 25 '16 at 12:48
  • @Lautaro, I've tagged your question as Unity3D, there's likely to be something already there for such scenarios. Failing that, this should get you going in the right direction: http://stackoverflow.com/a/493517/440704 – Nathan Apr 25 '16 at 13:01
  • Hi @Nathan indeed it's utterly built-in to Unity. (LoadAll) Question is unfortunately a bit of a time waste. It's one of the most common things you type in Unity, example `ra = Resources.LoadAll("path/", typeof(WhateverYouWant) ).Cast< WhateverYouWant >().ToArray();` – Fattie Apr 25 '16 at 14:49
  • (Note there are only like "two or three" possibilities of what you can load (images, audio file .. maybe text I guess) so in the unusual case you for some reason needed to choose between the two you'd use an if statement or some other trivial soluton.) – Fattie Apr 25 '16 at 14:50
  • 1
    @JoeBlow I would like to ask you not to be so condescending. I promise you i have already read all the links provided by others. Please explain what "WhateverYouWant" is in your example and how to use it? This is how i imagine it, which does not work. var myType = Type.GetType("AudioClip"); var ra = Resources.LoadAll("path", typeof(myType)).Cast< myType>().ToArray(); – Daarwin Apr 25 '16 at 15:03
  • 1
    @Nathan i appreciate your support. I didnt make the question Unity3D specific cause i thought i could learn something more fundamental of C# programming from it. But from your link i think now maybe it cant be done the way i was thinking of doing for Unity3D specific reasons. I may be better of with maybe a switch statement and 2-4 different options. Thanks! – Daarwin Apr 25 '16 at 15:07
  • @Lautaro: `typeof` is a compile-time construct that takes a type name, not a variable name, so `typeof(myType)` is invalid. However, `myType` is already of type `Type`, so you can pass it directly to `LoadAll`. `Cast<>` also requires a type name, so `Cast` is also invalid. Then again, casting is only useful if the type is known at compile-time. That's why I was asking: what do you intend to do with the results? – Pieter Witvoet Apr 26 '16 at 07:13