0

So I have a method that Creates a new object like so:

public class Objects<TObject>
{
    public NodeReference<TObject> CreateObject<TObject>(TObject objectType) 
                where TObject: class, new()
            {
                NodeReference<TObject> nodeReference = 0;

                return nodeReference;
            }
}

Now I have other object classes that define other object type like, Car.

public class Car
{
    public int NumberOfDoors {get; set;}
    public int NumberOfWheels {get; set;}
}

Now lets say I get passed a string how would I convert this string into its type at runtime?

var carObjectReference = CreateObject<//string converted to identify object car dynamically>(//new Car { });

Mike Barnes
  • 4,217
  • 18
  • 40
  • 64
  • You will need to use an `Activator` class. Have a look at [this answer](http://stackoverflow.com/a/7598427/706456) – oleksii Sep 26 '13 at 11:48
  • If you can convert your string to a `Type`, then you can continue with the techniques shown here: http://stackoverflow.com/questions/1408120/how-to-call-generic-method-with-a-given-type-object – Cᴏʀʏ Sep 26 '13 at 11:48
  • Possible duplicate of: http://stackoverflow.com/questions/1044455/c-sharp-reflection-how-to-get-class-reference-from-string – Surfbutler Sep 26 '13 at 11:49
  • possible duplicate of [How to use reflection to call generic Method?](http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method) – nawfal Jan 17 '14 at 12:48

1 Answers1

1
public object ReturnValue(string operationName, object returnValue)
{
    Type t = returnValue.GetType();
    return Activator.CreateInstance(t);
}
Taryn
  • 242,637
  • 56
  • 362
  • 405