Search code examples
c#.netgenericsobjectinstantiation

Create object of parameter type


hey. Is it possible to have a method that allows the user to pass in a parameter of a certain type and have the method instantiate a new object of that type? I would like to do something like this: (I don't know if generics is the way to go, but gave it a shot)

    public void LoadData<T>(T, string id, string value) where T : new()
    {

        this.Item.Add(new T() { ID=id, Val = value});

    }

The above doesn't work, but the idea is that the user passes the object type they want to instantiate and the method will fill in details based on those parameters. I could just pass an Enum parameter and do a Switch and create new objects based on that, but is there a better way? thanks


Solution

  • The only way to do this would be to add an interface that also specifies the parameters you want to set:

    public interface ISettable
    {
        string ID { get; set; }
        string Val { get; set; }
    }
    
    public void LoadData<T>(string id, string value) where T : ISettable, new()
    {
        this.Item.Add(new T { ID = id, Val = value });
    }
    

    Unfortunately I can't test to verify at the moment.