Quote:
viewTrains(string source,string destination):List<itrain>
This doesn't "look right" in the sense it is not valid C# code. It looks like a method declaration, but it isn't.
A primary use of Interfaces is to enable having a Collection of different Types of object instances cast to the same Interface Type(s) they have inherited; I assume that's what this question is really about.
edit: for information on how to serialize a collection of different Class instances that share a common Interface as a collection of Interface "instances:" see this post: [
^].
So, you need to implement some Classes that inherit from ITrain, and have their own unique Properties, or Fields, or Methods:
public class RegularTrains : ITrain
{
public int YearsInService { get; set; }
public RegularTrains(int id, string name, string source, string dest, int yrsservice)
{
YearsInService = yrsservice;
}
}
public enum TechnologyType
{
Maglev,
InternalCombustion,
Other
}
public class HighSpeedTrains : ITrain
{
public TechnologyType TechType { get; set; }
public HighSpeedTrains(int id, string name, string source, string dest, TechnologyType techtype)
{
TechType = techtype;
}
}
Now the question is: where and how do you create and store a list of all the Trains. One way is like this:
public static class AllTrains
{
public static List<ITrain> Trains { set; get; }
public static List<ITrain> ViewTrains(string source, string destination)
{
}
}
So, here you have a static class that keeps a Collection of Trains cast to their ITrain form. Now how does the list get items added; one way is to use the inheriting classes constructors:
public RegularTrains(int id, string name, string source, string dest, int yrsservice)
{
YearsInService = yrsservice;
AllTrains.Trains.Add(this);
}
Then, you can do something like this:
RegularTrain rtrain = new RegularTrain(1,"r1","Topeka", "Chicago", 14);
HighSpeedTrain strain = new HighSpeedTrain(2, "h1", "Topeka", "Chicago", TechnologyType.Maglev);
var allTrains = AllTrains.ViewTrains("Topeka", "Chicago");
Note that adding the new instance of the RegularTrain Class to the static List of ITrain did not require casting the instance to Type ITrain: the conversion is implicit in the Type system.
When you cast an object to an Interface it inherits from, essentially you have created a "view" of the object: that view restricts you to seeing (accessing) only the Properties or Methods declared in the Interface: the object is still "there" with all its unique fields, properties, methods: it has not been copied.
Use IntelliSense in Visual Studio to examine the List of ITrain, and look at a specific item, and you can get an idea of how Reflection can look beyond the interface into the fundamental Type.