Hey! Im doing a project, where i have to manage a bunch of different appliences.
I´ve made a custom generic collection class that has a few different search methods. Now the collection class has to hold all of the different appliances (so they all inherits from the same superclass: Appliance). I can't see how the search methods can return anything but an object of the superclass, so when they return that i would like to be able to cast it to the actual appliance. The only way i can see how that is possible is to make an if-else chain that checks on the object returneds type and then casts it from there.
Initially i thought you could use Type
to actually create an object and cast, but that isn't the case. You could do it with generic method, but then that would return an object that i dont know the type of.
Basically the code where im having the problem looks like this:
/.../
//the searching method in my generic class, the _wrappedList is the private list used to store the data
public List<Appliance> FindPriceRange(double min, double max){
List<Appliance> tmp = new List<Appliance>();
foreach (Appliance app in _wrappedList)
if (app.Price > min && app.Price < max)
tmp.Add(app);
return tmp;
}
/.../
/.../
//this is the code where i call the method and would like to cast the Appliance returned, to their actual sub-type
foreach (Appliance app in Appliances.FindPriceRange(750, 840)) {
Console.WriteLine(app.Name + " " + app.Price + "\n");
//conevert appliance to its sub-type
//basically; typeof(app) MySubClass =(typeof(app)) app;
//which i know doesnt work because you cant creat objects like that, but is there a way to do the same thing?
}
Thanks a bunch in advance. :)