C#
C#

help

Root Question Message

DeaDo
DeaDo10/19/2022
Is there a good way to use a object from Type Type in a generic method?

  Type type = typeof(object);
  GenericMethod</*use Type here*/>(); 


I have a lot of serialized different Objects in a Database along with their typename as string. All of them share the same Interface. Now i want to deserialize all of those to the right Objects.
Therefore i created a Application scanner that collects the Types for all those objects. Now i want to compare the typenames and deserialize them in a loop.
All of this feels wrong.

private IInterface GetObject(StoredObject storedObject)
        {
            foreach(var type in TypeList)
            {
                if(type.Name == storedObject.Type)
                    return JsonConvert.DeserializeObject</*TheCorrectType*/>(storedObject.ActualObjectData);
            }
        }

sth. like this
DeaDo
DeaDo10/19/2022
the storedObject contains the typename as string and the actual object as string
mtreit
mtreit10/19/2022
There is a non generic overload that takes the Type object as a method parameter. If you can have a mapping of strings to the actual type objects (like a dictionary or even just a switch expression) you can use that maybe?
Angius
Angius10/19/2022
Generics need to be known at compile time
mtreit
mtreit10/19/2022
Not if you're willing to write very gnarly reflection code :when:
Angius
Angius10/19/2022
Shhh
mtreit
mtreit10/19/2022
But yes generally don't do that
DeaDo
DeaDo10/19/2022
Thx.
ContactFrequently Asked QuestionsJoin The DiscordBugs & Feature RequestsTerms & Privacy