Search code examples
c#interfaceimplements

Casting class object to interface C#


I'm wondering what opportunities casting class object to interface that it implements from gives? For example:

     public interface IOwner
        {
            int Owner { get; set; }
        }

      public interface IArmy
        {
            Army Army { get; set; }
        }

      public interface ITreasure
        {
            Treasure Treasure { get; set; }
        }

      public class Creep : IOwner, IArmy, ITreasure
       {
        public int Owner { get; set; }
        public Army Army { get; set; }
        public Treasure Treasure { get; set; }   
       }

and class that works with it:

public static class Interaction

{
    public static void Make(Player player, object mapObject)
    {
        if (mapObject is IArmy)
            if (player.CanBeat(((IArmy)mapObject).Army))
            {
                if (mapObject is IOwner)
                    ((IOwner)mapObject).Owner = player.Id;
                if (mapObject is ITreasure)
                    player.Consume(((ITreasure)mapObject).Treasure);
            }

So now when I call this line: (player.CanBeat(((IArmy)mapObject).Army)) do I get access to Army field from mapObject class? It's obviously not interface's field since we can't work with them. Thanks in advice!


Solution

  • When you cast mapObject to IArmy interface it still stays mapObject class (Creep) on the inside but you can only call what is implied by IArmy interface.

    If you ask why and how it can be used: you can create another class that implements IArmy interface and when you cast it to IArmy you can process it the same way as the other classes that implement it.