Optimistic Peach
Optimistic Peach

Reputation: 4318

How to access members of an inherited object from a base

I am sorry for the unclear title, I wasn't really sure how to word it.
I have an interface; lets call it Iinterface;

public interface Iinterface
{
    //Some members
}

I also have an abstract class that inherits from Iinterface; lets call this one Aabstract, and this one has a method called dosomething().

public abstract class Aabstract : Iinterface
{
    public void dosomething()
    {

    }
}

I have a List<Iinterface> called listofIinterfaces in a part of my code in which each Iinterface may or may not be an Aabstract
How might I do something like the following (but working)

foreach (Iinterface a in listofIinterfaces)
{
    if (a is Aabstract)
    {
        a.dosomething();
    }
}

Upvotes: 0

Views: 26

Answers (1)

Evan Trimboli
Evan Trimboli

Reputation: 30092

As suggested in the comments, you can use as to attempt to cast the appropriate type:

namespace Sample {
    public interface IThing {

    }

    public class Type1 : IThing {
        public void Foo() { }
    }

    public class Type2 : IThing {
        public void Bar() { }
    }

    public class Program {
        static void Main(string[] args) {
            var list = new List<IThing> {
                new Type1(),
                new Type2()
            };

            foreach (var item in list) {
                var t1 = item as Type1;
                if (t1 != null) {
                    t1.Foo();
                }
            }
        }
    }
}

If you're using C# 7.0 you can also switch on type, the example is taken from here:

switch(shape)
{
    case Circle c:
        WriteLine($"circle with radius {c.Radius}");
        break;
    case Rectangle s when (s.Length == s.Height):
        WriteLine($"{s.Length} x {s.Height} square");
        break;
    case Rectangle r:
        WriteLine($"{r.Length} x {r.Height} rectangle");
        break;
    default:
        WriteLine("<unknown shape>");
        break;
    case null:
        throw new ArgumentNullException(nameof(shape));
}

Upvotes: 2

Related Questions