Reputation: 5945
I have a following problem:
I have interface ILocation, which includes functions to get position of feature (in 2D grid). Not all classes can have this interface, but those, which do, are not related to each other (do not inherit from each other etc.). I.e. classes with this interface are Person, Item, BuildingBlock...
Now I have class Location, which includes variable "block". Basically anything can be there, with one condition: it must implement interface ILocation. How can I do that? I do not know, which class will be in this variable, and therefore have to specify it as an Object, but I know, it must implement ILocation. How can this be done?
In following example, I want to implement method Symbol, which is in ILocation interface.
public class Location :ILocation
{
public int X {get; set;}
public int Y {get; set;}
public Object block;
public Location (int x, int y, Object o)
{
X = x;
Y = y;
block = o;
}
public char Symbol()
{
return block.Symbol();
}
}
And this of course produces an Error, since instance block of class Object does not implement ILocation.
So - how can I tell C#, that in variable "block" can be any object, which implements ILocation?
Thanks
Zbynek
Upvotes: 1
Views: 94
Reputation: 7277
Replace Object with ILocation.
public ILocation block;
public Location (int x, int y, ILocation o)
So whenever you make object of Location you can pass any object which implements ILocation interface.
var book = new Book(); // Book implements ILocation.
var person = new Person(); // Person implements ILocation.
var table = new Table(); // Table doesn't implement ILocation.
var bookLocation = new Location(1, 2, book);
var personLocation = new Location(2, 3, person);
var tableLocation = new Location(2, 3, table); // Compile error as table doesn't implement ILocation,
Upvotes: 0
Reputation: 1371
Either what lazyberezovsky said or, if you also need to keep knowledge of the exact type of block, you can use something with generics like:
public class Location<TBlock> : ILocation
where TBlock : ILocation
{
public int X { get; set; }
public int Y { get; set; }
public TBlock block;
public Location(int x, int y, TBlock o)
{
X = x;
Y = y;
block = o;
}
public char Symbol()
{
return block.Symbol();
}
}
Upvotes: 0
Reputation: 236208
Declare block variable as location:
public ILocation block;
public Location (int x, int y, ILocation o)
{
X = x;
Y = y;
block = o;
}
Upvotes: 5