NWoodsman
NWoodsman

Reputation: 505

Pass Arguments to Class stored in Dictionary

I would like to store a dictionary of derived objects (all from same base) along the lines of

Dictionary<Type,BaseClass> Dict = new Dictionary<Type,BaseClass>()
{
  {typeof(string), new Item1fromBaseClass()}
  {typeof(bool), new Item2fromBaseClass()}
  ...
};

I don't know how to pass this structure the arguments - the constructor necessarily looks like Item1fromBaseClass = new Item1fromBaseClass(Type t, object o) The good news is that the signature will be the same for every class. I have successfully tested with no parameters. Is this possible? What does the initializer for the dict look like?

Edit to add: given a BaseClass object i in another class, I need to be able to

i = Dict[typeof(string)]; //Args?
//i is now an instance of Item1fromBaseClass(Type t,object o)

Upvotes: 0

Views: 179

Answers (2)

Peter Duniho
Peter Duniho

Reputation: 70691

I'm afraid this question is not very clear. However, it sounds like the issue you are having is that you need to retrieve the BaseClass value at some later point in time, and the object o parameter to the constructor is not known until that time.

If so, then you will need to defer construction of the BaseClass object until that time. After all, otherwise how would you know what the o value is?

That would look something like this:

Dictionary<Type, Func<object, BaseClass>> Dict = new Dictionary<Type, Func<object, BaseClass>>()
{
  {typeof(string), o => new Item1fromBaseClass(typeof(string), o) },
  {typeof(bool), o => new Item2fromBaseClass(typeof(bool), o) },
  ...
};

Then you could use it like this:

// The object parameter for the constructor
object o = ...;

i = Dict[typeof(string)](o);

If that does not address your question, please improve the question so that it is more clear. Provide a good Minimal, Complete, and Verifiable code example that shows clearly what you are trying to do. State in precise terms what that code does now, and what you would like for it to do instead.

Upvotes: 0

Enigmativity
Enigmativity

Reputation: 117134

I think you're looking for this:

Dictionary<Type, Func<Type, object, BaseClass>> Dict = new Dictionary<Type, Func<Type, object, BaseClass>>()
{
    { typeof(string), (t, o) => new Item1fromBaseClass(t, o) },
    { typeof(bool), (t, o) => new Item2fromBaseClass(t, o) },
};

Then you can write:

i = Dict[typeof(string)].Invoke(type, obj);

Upvotes: 1

Related Questions