Reputation: 1974
Say I have a class who's constructor takes its values from data read from a file, is it also possible to create an instance of that class with a name from a string. That way I can create an instance of a class for each file I open and the constructor can be automatically loaded.
//User chooses file to open
//Read ChocolateCake.txt values
string className = Path.GetFileName(path);
//code to remove .txt
//Instance name is taken from className
Cake "ChocolateCake" = new Cake(ingredient1, ingredient2, etc);
How would I create an instance of Cake with the name of the file I have read?
Upvotes: 1
Views: 110
Reputation: 3799
Sometimes when I see issues like this which require some sort of object responsible for creating an appropriate type (e.g. Cake in your instance), based on input (in your case string), yes a Dictionary is a good starting place, but I always feel this is an indicator to look into a more flexible approach, e.g. using the Factory pattern.
Factories build objects. They usually do this using some parameter(s) that help decide what type of concrete object to build. The return type of a factory is often some kind of abstraction, i.e. an interface or an abstract class and the factory builds a concrete implementation of the abstraction.
This means you can have lots of different types of Cake object, and the factory return the correct one based on whatever is defined in your input string. One of the important benefits is the caller doesn't need to know up front what concrete type is expected, it will operate with an interface type instead meaning you don't need to keep updating the caller's code when new "Cake" types are added.
It's worth reading about abstract class factories, this is a nice little introduction.
Upvotes: 1
Reputation: 54117
No, you cannot do this. You could however use a generic Dictionary<string, Cake>
and store your cakes in that...
var cakes = new Dictionary<string, Cake>();
This cakes
variable will hold multiple objects of type Cake
, each keyed by a unique string
value.
Adding a cake is as simple as...
cakes.Add("ChocolateCake", new Cake(incredient1, incredient2, etc));
And you can then access your cakes by key value (e.g. class name in your example), thus:
cakes["ChocolateCake"];
Upvotes: 4
Reputation: 136114
You could use a dictionary,
var cakes = new Dictionary<string,Cake>();
cakes.Add(className, new Cake(ingredient1, ingredient2));
Upvotes: 4