zaza
zaza

Reputation: 912

Get T from Type object

I have a method that requires a T to function properly. I have a Type object as a property of my class.

public Type DefaultNumaricType {get; private set;} = typeof(double);

private T Convert<T>(string input)
{
    ...
}

I want to be able to call the Convert<T> method and get an object of the type specified in DefaultNumaricType.

Is something like this possible:

double d = Convert<DefaultNumaricType>("123.00");

Upvotes: 1

Views: 127

Answers (1)

Enigmativity
Enigmativity

Reputation: 117027

Is is possible that you'd like something like this?

var converter = new Converter();

converter.Configure<double>(x => double.Parse(x));
converter.Configure<int?>(x => int.TryParse(x, out int result) ? (int?)result : null);

var value1 = converter.Convert<double>("42.123");
var value2 = converter.Convert<int?>("");

If so, here's the class that does it:

public class Converter
{
    private Dictionary<Type, Delegate> _factories = new Dictionary<Type, Delegate>();

    public void Configure<T>(Func<string, T> factory)
    {
        _factories[typeof(T)] = factory;
    }

    public T Convert<T>(string input)
    {
        return ((Func<string, T>)_factories[typeof(T)])(input);
    }
}

Upvotes: 1

Related Questions