views:

57

answers:

3

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

+1  A: 

If the ID and Val properties come from a common base class or interface, you can constrain T to inherit that type.

For example:

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

You can then use all the members of IMyInterface on T instances.

If they're just unrelated properties in different types that happen to have the same name, you'll have to use reflection.

Also, you need to remove T, from your parameter list.

SLaks
Thanks for the help.
SSL
+4  A: 

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.

Justin Niessner
The properties are contracted with an interface.
SSL
@SSL - Then as long as the interface also requires setters, you just need to add that interface to the constraints.
Justin Niessner
Thanks, this works perfectly.
SSL
A: 

A more dynamically typed language could do that with ease. I'm sure its possible with C#, it'll just take more effort. Theres probably some reflection library that will help you here.

Why don't you just create the object when you are calling the method? What you are trying to do seems way overly complex to me.

toc777
The code was pretty straightforward in C# as well. Pretty much one line for my application. I don't know what the object type is, which was the problem.
SSL
But you must know the object type when you call the method for it to work.
toc777
Now that your using an interface it seems to me like you could do away the generics and just rely on the interface.
toc777