1

I have 4 public classes, with a bunch of properties each: MoveUpdateEntry, FullServiceEntry, SeamlessAcceptanceEntry, and UndocumentedEntry.

I have a dictionary containing excerpts of a given filename, along with a correlation in place to determine the string equivalent of the class's name I need to instantiate:

private static Dictionary<string, string> dEntryCorr = new Dictionary<string, string>()
{
    {"MU_MU", "MoveUpdateEntry" },
    {"FS_BQ", "FullServiceEntry" },
    {"FS_BF", "FullServiceEntry" },
    {"SE_NS", "SeamlessAcceptanceEntry" },
    {"SE_U_", "UndocumentedEntry" }
};

I've tried using Reflections as stated here, but simply trying to run the following gives me an error:

string fileToProcess = "MU_MU.json";
Type entryType = Type.GetType( dEntryCorr[ fileToProcess.Substring(0,5) ], true );

System.TypeLoadException: 'Could not load type 'MoveUpdateEntry' from assembly 'DataLoaderJSON, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.'

My end goal here is to be able to dynamically pick a type to make a List<> of, based on the filename. (e.g. MU_MU.json will create List<MoveUpdateEntry>, FS_BQ.json creates List<FullServiceEntry>, etc.)

Is this possible in C#?

TLDR: I want to create a List<> with a class type that is determined by a string. This is a matter of abstraction.

7
  • Are you asking how to create create an instance of a generic type at run time or are you asking how to load dlls? They are different questions. Commented Aug 7, 2020 at 0:22
  • @AluanHaddad I'm asking how I create a list of a custom class by its string name, or at the very least instantiate an instance of that very class Commented Aug 7, 2020 at 0:25
  • string typeName = "Namespace." + dEntryCorr[fileToProcess.Substring(0, 5)] + ", Assembly";. See this answer. Commented Aug 7, 2020 at 0:25
  • Just when serializing, use typeof(MoveUpdateEntry).AssemblyQualifiedName Commented Aug 7, 2020 at 0:29
  • 1
    While it is possible to instantiate a type-specific List<T> and assign it to a dynamic or object variable, I'm not sure that will help you meet your goals-- at compile time, your code will have no idea what type the list is so you won't be able to do anything useful with it. You may as well just use a List<object> or a List<dynamic>. Commented Aug 7, 2020 at 0:55

1 Answer 1

1

One way to get a Type from a string:

        string fileToProcess = "MU_MU.json";
        var entryType = AppDomain.CurrentDomain
            .GetAssemblies()
            .SelectMany(x => x.GetTypes())
            .FirstOrDefault(t => t.Name == dEntryCorr[fileToProcess.Substring(0, 5)]);

(If there are more than one Type with the name entryType will only contain one of them.)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.