Wednesday, 11 September 2013

Difference between using 'dynamic' vs base type when instantiating object

Difference between using 'dynamic' vs base type when instantiating object

I am somewhat confused as to what the best approach would be when it comes
to creating a new object when the type of this object is unknown until run
time. Suppose I have a base class called Animals in the following manner:
public class Store
{
public Store()
{
Inventory = new List<Inventory>()
}
public string Title { get; set;}
public ICollection<Inventory> Inventory { get; set; }
}
Now suppose that I have another class which implements the Store class,
let's call it, PetStore. In PetStore, I define a constructor, which is
called whenever the StoreFactory creates an object:
PetStore
public PetStore(Store store)
: base(store)
{
Title = ((PetStore)store).Title;
}
Using StoreFactory and reflection to instantiate an object:
public static Store FromTemplate(Store store)
{
Type type = Type.GetType(store.StoreType.ClassName);
Store newstore = Activator.CreateInstance(type, store) as Store;
return newstore;
}
To get to the heart of the question now; what is the difference in
instantiating and object by doing the following:
Store newStore = StoreFactory.FromTemplate(existingPetStore);
and
dynamic newStore = StoreFactory.FromTemplate(existingPetStore);
I am not sure if I'm wording the question properly or might be a bit
confusing, I apologize if that's the case. Otherwise, I am looking to
understand how MVC differentiates between these two and ultimately, which
is the best approach to use in this case.
Thank you!

No comments:

Post a Comment