Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to store a Func<T> within a dictionary?

I'd like to be able to implement a dictionary with a key of Type and a value of Func<T> where T is an object of the same type as the key :

Dictionary<Type, Func<T>> TypeDictionary = new Dictionary<Type, Func<T>>( ) /*Func<T> returns an object of the same type as the Key*/

TypeDictionary.Add( typeof( int ), ( ) => 5 );
TypeDictionary.Add( typeof( string ), ( ) => "Foo" );

So, basically, the dictionary would be populated with types that would reference a Func<T> which would return that value :

int Bar = TypeDictionary[ typeof( int ) ]( );
string Baz = TypeDictionary[ typeof( string ) ]( );

How can I go about implementing and enforcing this?

like image 222
Will Avatar asked Jun 20 '16 00:06

Will


1 Answers

This is about as close as you're going to get:

void Main()
{
    var myDict = new MyWrappedDictionary();
    myDict.Add(() => "Rob");
    var func = myDict.Get<string>();
    Console.WriteLine(func());
}

public class MyWrappedDictionary
{
    private Dictionary<Type, object> innerDictionary = new Dictionary<Type, object>();
    public void Add<T>(Func<T> func)
    {
        innerDictionary.Add(typeof(T), func);
    }
    public Func<T> Get<T>()
    {
        return innerDictionary[typeof(T)] as Func<T>;
    }
}
like image 183
Rob Avatar answered Sep 30 '22 17:09

Rob