Si-Malik
Si-Malik

Reputation: 49

Passing Type to Method (w/o Generic) (C# Syntax)

I've been looking for a way to create a temporary variable in the construction of a database manager.

public void Read(string name, string info, Type type){
    // blah temp = "Create temporary variable of type above"
    database.retrieve(name, info, out temp);
    Debug.Log (temp.ToString());
}

I tried passing Generics, but JSON doesn't like methods with Generics. I feel like I'm on the verge of figuring it out with typeof, but I can't seem to find the syntax.

Edit: The temporary variable contains an overriden ToString(), so I can't simply out to and Object.

Upvotes: 0

Views: 132

Answers (2)

Vadim K.
Vadim K.

Reputation: 1101

You can try something like this. But this example assumes that your type has parameterless constructor. If you use .NET < 4.0 change dynamic to Object.

    public void Read(string name, string info, Type type)
    {
        ConstructorInfo ctor = type.GetConstructor(System.Type.EmptyTypes);
        if (ctor != null)
        {
            dynamic temp = ctor.Invoke(null);
            database.retrieve(name, info, out temp);
            Debug.Log(temp.ToString());
        }
    }

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564323

If database.retrieve is a generic method, the best option would be to make the method itself generic:

public void Read<T>(string name, string info)
{
     T temp;
     database.retrieve(name, info, out temp);
     // ...
}

Since it's an out parameter, you don't actually need to instantiate a temporary. If it's non-generic, and takes object, just use object:

public void Read(string name, string info, Type type)
{
     object temp;
     database.retrieve(name, info, out temp);
     // ...
}

Upvotes: 3

Related Questions