I'm trying to create an interface for a model class in ASP.NET MVC2 and I wonder if I can use a List<interface>
within another interface. It's better if I give a code example.
I have two interfaces, a terminal can have multiple bays. So I code my interfaces like the following.
Bay Interface:
public interface IBay
{
// Properties
int id {get; set;}
string name {get;set;}
// ... other properties
}
Terminal Interface:
public interface ITerminal
{
// Properties
int id {get;set;}
string name {get;set;}
// ... other properties
List<IBay> bays {get;set;}
}
My question is when I implement my class based on these interfaces how to I set up the list of bays. Am I going to have to do the list of bays outside the ITerminal interface and inside the concrete implementation?
My goal is to be able to do the following:
Concrete implementation:
Bay Class:
class Bay : IBay
{
// Constructor
public Bay()
{
// ... constructor
}
}
Terminal Class:
class Terminal : ITerminal
{
// Constructor
public Terminal()
{
// ... constructor
}
}
And then be able to access the list of bays like this
Terminal.Bays
Any help/suggestions would be greatly appreciated.
Interfaces can inherit from one or more interfaces. The derived interface inherits the members from its base interfaces. A class that implements a derived interface must implement all members in the derived interface, including all members of the derived interface's base interfaces.
The main difference between List and IList in C# is that List is a class that represents a list of objects which can be accessed by index while IList is an interface that represents a collection of objects which can be accessed by index.
Because interfaces can be implemented by multiple components, it's good practice to put them in a separate assembly from that of the implementing components.
Since List is an interface, objects cannot be created of the type list. We always need a class that implements this List in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the List.
You can initialize a list-of-interface by populating it with concrete instances. For example, to initialize your Terminal
class using object and collection initializers, you could use code similar to:
Terminal terminal = new Terminal
{
id = 0,
name = "My terminal",
bays = new List<IBay>
{
new Bay { id = 1, name = "First bay" },
new Bay { id = 2, name = "Second bay" },
new Bay { id = 3, name = "Third bay" },
}
};
Some points about your code:
Id
or ID
instead of id
; Name
instead of name
; Bays
instead of bays
.bays
property from List<IBay>
to IList<IBay>
. This would allow consumers to assign IBay[]
arrays to it.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With