Arin Bryan
Arin Bryan

Reputation: 29

Creating constructors with unknown typed arguments

I'm making a class

class token
{
    public string name; //Known Type
    public ?????? value; //Unknown Type until runtime
    public token(string name, ????? value)
    {
        self.name = name;
        self.value = value;
    }
}

What would the correct type(?) of value be to allow data of any type to be input as an argument to the constructor when the class is instantiated?

Upvotes: 0

Views: 206

Answers (1)

groogiam
groogiam

Reputation: 309

You're looking for generics (reference):

class token<T>
{
    public string name; //Known Type
    public T value; //Unknown Type until runtime
    public token(string name, T value)
    {
        this.name = name;
        this.value = value;
    }
}

Usage:

var myToken = new token<string>("Name", "Value");

In response to the comment below: This is how you could create the type dynamically at runtime. Please note that Activator.CreateInstance can be rather slow so you would want to avoid calling it inside of a loop.

var someDynamicType = typeof(string);
var someDynamicValue = "Value";

var type = typeof(token<>).MakeGenericType(typeof(string));
var myObject = Activator.CreateInstance(type, "Name", someDynamicValue);

Upvotes: 2

Related Questions