I have the following interface
public interface ITypedValueProvider<TValue>
{
TValue GetValue(Type type);
}
I want to create extension method which would allow me to get type from generic type argument. I have written an extension method like following.
public static class Extensions
{
public static TValue GetValue<TType, TValue>(this ITypedValueProvider<TValue> valueProvider)
{
return valueProvider.GetValue(typeof(TType));
}
}
However, this extension method requires 2 type arguments, where I need to use only one, and hopefully other be inferred from the input generic class.
static class Program
{
void Main()
{
ITypedValueProvider<int> valueProvider = new ValueProvider<int>(typeof(TargetValueConsumer));
var value = valueProvider.GetValue<TargetValueConsumer, int>() //This line will work
var value = valueProvider.GetValue<TargetValueConsumer>(); //This one, obviously, won't compile
}
}
public class ValueProvider<TValue> : ITypedValueProvider<TValue>
{
private readonly (Type ConsumerType, TValue Value) _record;
public ValueProvider(TValue value, Type type)
{
_record = (type, value);
}
TValue GetValue(Type type)
{
if (_record.ConsumerType == type)
return _record.Value;
return default;
}
}
public class TargetValueConsumer {}
How can I write the extension method which won't require second type argument for the described interface or how to use existing method which will infer second type argument from the usage?
